Python Changing Chart Legend Colors - Openpyxl

2019-08-13 09:59发布

Is it possible to change the color associated with the legend of a chart created in Openpyxl?

I have created a relatively simple chart using my data but would like to force the colors it uses to create each piece. Here's the snippet of my code related to the chart:

chart = PieChart()
data = Reference(worksheet, min_col=2, min_row=4, max_row=7, max_col=2)
categories = Reference(worksheet, min_col=1, min_row=4, max_row=7, max_col=1)

chart.add_data(data)
chart.set_categories(categories)

worksheet.add_chart(chart, 'D3')

2条回答
smile是对你的礼貌
2楼-- · 2019-08-13 10:10

The easiest way to change the color is to change the color scheme via styles:

chart.style = 5

There are two other ways that I have not looked into but you may be able to modify the colors using more obscure methods.

The first is through the a member in this class:

openpyxl.ledgend.Legend

The spPr member which is expecting GraphicalProperties to be assigned and you may be able to modify this to change the color.

The second possibility is to create your own style and assign it using the previously mentioned command.

查看更多
看我几分像从前
3楼-- · 2019-08-13 10:21

If you want to change the colors of each series in the legend, you should change the color of the lines for each series in your plot using something like this:

series.graphicalProperties.line.solidFill = Color

from openpyxl.chart import ScatterChart, Reference, Series

# Set up basic XY Scatter Chart
chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 2 # Excel menu chart tools: Design > Chart Styles > picked second style

# setup the X-axis series (A2:A7). Notice that header is excluded in range by starting on row 2.
xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)

# setup, style and append the first series (B1:B7)
values = Reference(ws, min_col=2, min_row=1, max_row=7)
series = Series(values, xvalues, title_from_data=True)
series.smooth = True
series.graphicalProperties.line.width = 50000
series.graphicalProperties.line.solidFill = 'FF0000' # Red
chart.append(series)
查看更多
登录 后发表回答