??盡管R語言是進行生態環境數據探索的首選,但Excel無疑在我們搜集、整理以及初步數據探索中依舊有著十分重要的作用。繪制環境因子間的兩兩散點圖是探索因子關系的常見步驟,當環境因子較多時scatterplotMatrix()顯得力不從心,當因子間的關系不是簡單的線性關系時,corrplot()也不能完全展示數據間的關系。這里我們用python的openpyxl包控制excel繪制11個變量間的兩兩散點圖。
??效果如下:
主要步驟:
python計算兩兩相關性P值 python的openpyxl包控制excel繪制11個變量間的兩兩散點圖,并將P值寫入excel表格; VBA將P值添入散點圖,并修改為默認格式;
步驟代碼
步驟1的python代碼
xie = pd.read_excel("./Desktop/xie.xlsx")
p = np.zeros(55)
l=0
for i in range(0,10):for j in range(i+1,11):x=np.array(xie[xie.columns[i]])y=np.array(xie[xie.columns[j]])fit = stats.linregress(x,y)p[l] = fit.pvalueprint([l,p[l]])l=l+1
步驟2的python代碼:
from openpyxl import load_workbook
from openpyxl.chart import (ScatterChart,Reference,Series,legend,
)
from openpyxl.chart.text import (RichText,Text)
from openpyxl.drawing.text import (Paragraph, ParagraphProperties, CharacterProperties, Font,TextField
)
from openpyxl.styles import Border
from openpyxl.chart.trendline import (Trendline,TrendlineLabel)
from openpyxl.chart.title import title_makerwb = load_workbook('./Desktop/xie.xlsx')
ws = wb.active
k=0
for i in range(1,11):for j in range(i+1,12): chart = ScatterChart()chart.height = 6.42chart.width = 9.57chart.legend = Nonexv = Reference(ws, min_col=i, min_row=2, max_row=80)#print(i)yv = Reference(ws, min_col=j, min_row=2, max_row=80)series = Series(values = yv,xvalues = xv,title_from_data=False)chart.series.append(series)chart.title = ws.cell(1,i).value+" vs "+ws.cell(1,j).valuetitle_font = Font(typeface='Calibri')cp = CharacterProperties(latin=title_font, sz=900)cp2 = CharacterProperties(latin=title_font, sz=1400,b=False)pp = ParagraphProperties(defRPr=cp)pp2 = ParagraphProperties(defRPr=cp2)rtp = RichText(p=[Paragraph(pPr=pp, endParaRPr=cp)])chart.x_axis.txPr = rtpchart.y_axis.txPr = rtpchart.title.text.rich.paragraphs[0].pPr = pp2s1 = chart.series[0]s1.marker.symbol = "circle"#s1.marker.graphicalProperties.solidFill = "FF0000" # Marker filling#s1.marker.graphicalProperties.line.solidFill = "FF0000" # Marker outlines1.graphicalProperties.line.noFill = True # hide liness1.trendline=Trendline(trendlineType = 'linear',dispEq=True,dispRSqr=True)chartPosition = "N"+str(7*k+1)mycell = ws.cell(row=k+1, column=25)mycell.value = p[k]k=k+1ws.add_chart(chart, chartPosition)
wb.save("./Desktop/xie2.xlsx")
步驟3的VBA代碼:
Sub addPvalue()For i = 1 To 55ActiveSheet.ChartObjects(Index:=i).Activatea = ActiveChart.FullSeriesCollection(1).Trendlines(1).DataLabel.TextActiveChart.FullSeriesCollection(1).Trendlines(1).DataLabel.Text = (a & ";" & Cells(i + 1, 22))ActiveChart.ChartStyle = 240Next i
End Sub
測試數據和可參考如下鏈接 python openpyxl + excel VBA批量繪制兩兩散點圖
總結
以上是生活随笔 為你收集整理的python openpyxl + VBA控制Excel批量绘制两两散点图 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。