openpyxl 趋势线和 R 平方值

openpyxl trendline and R-squared value

我正在尝试将 "linear" 趋势线添加到我的 excel 图表并使用 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")

记录图表的所有可能性基本上是不可能的,因此您有时不得不深入研究相关图表的 XML 以了解它是如何完成的。也就是说,趋势线很容易做到。

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