python-3.x 更改图表图例颜色,建立自己的图表配色方案- Openpyxl 2.4.9

qhhrdooz  于 2023-01-10  发布在  Python
关注(0)|答案(1)|浏览(210)

我知道您可以使用.style = number更改图表颜色,但是现有的配色方案都不能满足我的需要。我想建立自己的图表配色方案。我想知道的是我应该在哪里这样做。库中的.style编号在哪里。如果我找到了这个,我可以通过查看.py文件中已经设置的内容来构建我自己的。我使用的是openpyxl 2.4.9。我将此作为参考:Python Changing Chart Legend Colors - Openpyxl

ni65a41a

ni65a41a1#

我也有同样的问题,我不知道**.style编号**在哪里,但是我从this answer创建了一个适合我的解决方案。

我做了一个饼图和一个水平条形图
---饼图求解---

from openpyxl.chart import PieChart, Reference
from openpyxl.chart.marker import DataPoint

wb = Workbook()
ws = wb.create_sheet(title='WorkSheet')

pie = PieChart()

values = Reference(ws, min_col=7, min_row=1, max_row=4)
labels = Reference(ws, min_col=8, min_row=2, max_row=4)

pie.add_data(values, titles_from_data=True)
pie.set_categories(labels)

pie.title = " Title "

# --- CHANGE COLORS ---

serie = pie.series[0]

# Inside the 'list' of the 'For' you just had to add the color's hexadecimal code
# that you want in your chart.
for i, color in enumerate(['3F71CA', 'ADADAD', '609FDB']):
    pt = DataPoint(idx=i)
    pt.graphicalProperties.solidFill = color
    serie.dPt.append(pt)

ws.add_chart(pie, "F5")

---水平条形图的解决方案---

from openpyxl.chart import BarChart, Reference
from openpyxl.drawing.colors import ColorChoice

#Create a new Workbook.
wb = Workbook()

#Select the active Worksheet.
ws = wb.active

# Data
rows = [
    ('val', 'Batch 1', 'Batch 2'),
    ('val_1', 10, 30),
    ('val_2', 40, 60),
    ('val_3', 50, 70),
    ('val_4', 20, 10),
    ('val_5', 10, 40),
    ('val_6', 50, 30),
]

# Adding data to worksheet.
for row in rows:
    ws.append(row)

#Create a new BarChart.
bar = BarChart()

#Add some properties.
bar.type = "bar"
bar.title = " Title"
# bar.height = 20
# bar.width = 20

#Add the data to the chart.
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
labels = Reference(ws, min_col=1, min_row=2, max_row=7)
bar.add_data(data, titles_from_data=True)
bar.set_categories(labels)

# --- SOLUTION --- Change bar colors.

#Put the hexadecimal code of the colors you want in a list.
colors = ['264478', '5B9BD5', 'A5A5A5', '4472C4']

#Iterate over the bar series and change the GraphicalProperties.
for i, s in enumerate(bar.series):
    s.graphicalProperties.solidFill = ColorChoice(srgbClr=colors[i])

#Add the chart to the worksheet.
ws.add_chart(bar, 'E7')

#Save the workbook.
wb.save('.\\result.xlsx')

Openpyxl版本:3.0.10

相关问题