2016-08-03 175 views
0

我正在嘗試將「線性」趨勢線添加到我的Excel圖表中,並使用openpyxl顯示R平方值,但我找不到任何示例。openpyxl趨勢線和R平方值

以下是生成圖像所顯示的圖表的Python代碼,沒有趨勢線和R平方公式chart image

謝謝!

from openpyxl import Workbook, load_workbook 
from openpyxl.chart import (
    ScatterChart, 
    Reference, 
    Series, 
) 
from openpyxl.chart.trendline import Trendline 


wb = load_workbook(r"path to load blank workbook\data.xlsx") 
ws = wb.active 

rows = [ 
    ['Size', 'Batch 1'], 
    [3, 40], 
    [4, 50], 
    [2, 40], 
    [5, 30], 
    [6, 25], 
    [7, 20], 
] 

for row in rows: 
    ws.append(row) 

chart = ScatterChart() 
chart.title = "Scatter Chart" 
#chart.style = 13 
chart.x_axis.title = 'Size' 
chart.y_axis.title = 'Percentage' 



xvalues = Reference(ws, min_col=1, min_row=2, max_row=8) 
for i in range(2, 4): 
    values = Reference(ws, min_col=i, min_row=2, max_row=8) 
    series = Series(values, xvalues, title_from_data=True) 
    chart.series.append(series) 



line = chart.series[0] 
line.graphicalProperties.line.noFill = True 
line.marker.symbol = "circle" 


ws.add_chart(chart, "A10") 

wb.save("path to save workbook\scatter.xlsx") 

回答

1

基本上不可能記錄圖表的所有可能性,因此您偶爾不得不深入到相關圖表的XML中以瞭解它是如何完成的。也就是說,趨勢線很容易做到。

from openpyxl.chart.trendline import Trendline 
line.trendline = Trendline() 
+0

謝謝查理!這正是我需要的。我添加了line.trendline = Trendline(dispRSqr = True)來顯示R平方值。 –