python - 使用 openpyxl 的时间进程堆积条形图

标签 python openpyxl

我想用 openpyxl 创建一个堆栈条形图。在我的 Excel 工作表上,每列都是一个时间点,包含不同类别的数据。从 openpyxl 教程来看,如果我每行都有每个时间点,那么创建条形图似乎很简单。但我没有自由切换行和列。有没有办法创建堆栈图,其中每个条形代表一个时间点,并且该时间点的每个类别都堆积起来?以下是一些示例数据:

sample data

我想创建一个类似的图表:

chart to create:

最佳答案

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

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

关于python - 使用 openpyxl 的时间进程堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524661/

相关文章:

Python 应用程序错误(Udacity)

python - Pandas:如何识别数据帧列中的值并进行一些数学运算

python - 不能让基于请求构建的脚本从网页生成所有图像链接

python - 循环 python openpyxl。如何在单元格中添加循环

python - 在 python 中打开 xlsx 文件时出错

Python type() 显示不同的结果

python - 如何将我的 multiprocessing.mangers.BaseManager 子类使用的序列化程序更改为 cPickle?

python - 如何在openpyxl中指定饼图楔形颜色?

python - 正常样式已存在 - Python - OpenPyxl

Python 2.7 : Check if excel file is already open in program before saving it