我正在尝试从特定的列值添加自定义的x轴刻度,
类似于饼图的set_categories
。我浏览了文档,但找不到任何解决方案。
下面是我的代码:
from openpyxl.chart import ScatterChart, Reference, Series
wb = openpyxl.Workbook()
sheet = wb.active
rows = [
("Number", "Sales", "Market") ,
("Number of Products", "Sales in USD", "Market share"),
('0x1', 12200, 15),
('0x2', 60000, 33),
('0x3', 24400, 10),
('0x4', 32000, 42),
]
for row in rows:
sheet.append(row)
chart = ScatterChart()
xvalues = Reference(sheet, min_col = 1, min_row = 3, max_row = 6)
yvalues = Reference(sheet, min_col = 2, min_row = 3, max_row = 6)
size = Reference(sheet, min_col = 3, min_row = 3, max_row = 6)
series = Series(values = yvalues, xvalues =xvalues , zvalues =size , title ="2013")
chart.series.append(series)
chart.title = " SCATTER-CHART "
chart.x_axis.title = " X_AXIS "
chart.y_axis.title = " Y_AXIS "
sheet.add_chart(chart, "E2")
wb.save(" ScatterChart.xlsx")
谁能告诉我如何在X轴刻度线中添加xvalues
。
这是我正在寻找的预期图形:
答案 0 :(得分:0)
我相信您的目标如下:
xvalues
添加到x轴刻度线观察:
ScatterChart
,并尝试使用字符串标签设置x轴刻度,此图表类型不支持此标签,仅支持数字值。解决方案
ScatterChart
更改为LineChart
(如果仍然有相同的目标,则将BarChart
更改。)修改后的解决方案代码:
from openpyxl import Workbook
from openpyxl.chart import LineChart
wb = Workbook()
sheet = wb.active
rows = [
("Number", "Sales", "Market") ,
("Number of Products", "Sales in USD", "Market share"),
('0x1', 12200, 15),
('0x2', 60000, 33),
('0x3', 24400, 10),
('0x4', 32000, 42),
]
for row in rows:
sheet.append(row)
# build chart
chart = LineChart()
# label chart
chart.title = " SCATTER-CHART "
chart.x_axis.title = " X_AXIS "
chart.y_axis.title = " Y_AXIS "
# define data series and domain range
xvalues = Reference(sheet, min_col = 1, min_row = 3, max_row = 6)
yvalues = Reference(sheet, min_col = 2, min_row = 3, max_row = 6)
# add data to chart
chart.add_data(yvalues)
chart.set_categories(xvalues)
sheet.add_chart(chart, 'E2')
# save file
wb.save('LineChart.xlsx')