使用Openpyxl Python 3.7在散点图中自定义X轴刻度

时间:2020-01-13 09:44:01

标签: python python-3.x openpyxl

我正在尝试从特定的列值添加自定义的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。 这是我正在寻找的预期图形:

enter image description here

1 个答案:

答案 0 :(得分:0)

我相信您的目标如下:

  • 您要将xvalues添加到x轴刻度线
  • 您要通过创建简单的折线图来做到这一点?

观察:

  • 您正在创建ScatterChart,并尝试使用字符串标签设置x轴刻度,此图表类型不支持此标签,仅支持数字值。

解决方案

  1. 将图表类型从ScatterChart更改为LineChart(如果仍然有相同的目标,则将BarChart更改。)
  2. 修改图表构建参数

修改后的解决方案代码:

  • LINE CHART
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')

Output chart image