Reputation: 23
I'm trying to add "linear" trend-line to my excel chart and display R-squared value using openpyxl, but i cannot find any example.
Below is python code that generates chart shown on image without trend-line and R-squared formula chart image.
Thanks!
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")
Upvotes: 2
Views: 2317
Reputation: 19527
It's basically impossible to document all the possibilities for charts so you will occasionally have to dive into the XML of a relevant chart to find out how it's done. That said, trendlines are pretty easy to do.
from openpyxl.chart.trendline import Trendline
line.trendline = Trendline()
Upvotes: 3