Python openpyxl Excel绘制柱形图(python中布尔类型的值是)
260
2022-07-31
这是一份openpyxl的使用指南。
大体内容翻译自官网 https://openpyxl.readthedocs.io/en/stable/charts/bar.html#vertical-horizontal-and-stacked-bar-charts
本文在官网基础上会有一些改动。代码请参考 https://github.com/RustFisher/python-playground
本文链接 https://rustfisher.com/2019/11/14/Python/Python-openpyxl_charts_Bar_and_Column/
柱形图
数据会被绘制成垂直,水平或者是层叠效果的柱形图。
注意:
接下来的设置会影响到不同类型的图表。
设置类别可以控制柱形图是垂直或是水平。
使用层叠图形时,需要设置overlap成100。
如果柱形是水平的,x和y坐标会对调过来。
2D图表
示例代码如下,根据给定的数据绘制了4张图表。
from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference
def bar_chart_demo():
wb = Workbook(write_only=True)
ws = wb.create_sheet()
rows = [
('Number', 'Batch 1', 'Batch 2'),
(2, 10, 30),
(3, 40, 60),
(4, 50, 70),
(5, 20, 10),
(6, 10, 40),
(7, 50, 30),
]
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")
from copy import deepcopy
chart2 = deepcopy(chart1)
chart2.style = 11
chart2.type = "bar"
chart2.title = "Horizontal Bar Chart"
ws.add_chart(chart2, "I10")
chart3 = deepcopy(chart1)
chart3.type = "col"
chart3.style = 12
chart3.grouping = "stacked"
chart3.overlap = 100
chart3.title = 'Stacked Chart'
ws.add_chart(chart3, "A27")
chart4 = deepcopy(chart1)
chart4.type = "bar"
chart4.style = 13
chart4.grouping = "percentStacked"
chart4.overlap = 100
chart4.title = 'Percent Stacked Chart'
ws.add_chart(chart4, "I27")
wb.save("out/bar.xlsx")
if __name__ == '__main__':
bar_chart_demo()
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~