使用openpyxl的时间课程stackbar图表

时间:2019-02-04 21:37:21

标签: python openpyxl

我想用openpyxl创建一个堆栈条形图。在我的Excel工作表上,每个col是一个包含不同类别数据的时间点。从openpyxl教程开始,如果我每行有每个时间点,创建条形图似乎很简单。但是我没有自由切换行和列。有没有一种方法可以创建一个带有每个时间点的每个条形图并堆叠该时间点的每个类别的堆栈图?以下是一些示例数据:

chart to create:

我想创建一个像这样的图表:

{{3}}

1 个答案:

答案 0 :(得分:1)

我将here中的示例修改为使用您的示例。主要更改是使用关键字参数add_data()告诉图表的from_rows=True方法,您拥有数据行而不是列。唯一的其他更改是行号和列号,以获取正确的引用。

from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

wb = Workbook(write_only=True)
ws = wb.create_sheet()

rows = [
    ('Mon/Cat', '2018-08', '2018-09', '2018-10', '2018-11'),
    ('Cat 101', 885, 3378, 0, 2155),
    ('Cat 102', 0, 458, 1255, 0),
    ('Cat 103', 474, 0, 1554, 1655),
    ('Cat 104', 1250, 250, 502, 845),
]


for row in rows:
    ws.append(row)


chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.grouping = "stacked"
chart1.overlap = 100
chart1.title = "Chart Title"
#chart1.y_axis.title = 'y-axis'
#chart1.x_axis.title = 'x-axis'

data = Reference(ws, min_col=1, min_row=2, max_row=5, max_col=5)
cats = Reference(ws, min_col=2, min_row=1, max_col=5)
chart1.add_data(data, from_rows=True, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")

wb.save("bar.xlsx")