Python Changing Chart Legend Colors - Openpyxl

前提是你 提交于 2019-12-24 17:12:05

问题


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')

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/32831100/python-changing-chart-legend-colors-openpyxl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!