import openpyxl
from openpyxl.chart import PieChart, Reference, BarChart, BubbleChart, ScatterChart
# Reference:图标所用信息
from openpyxl.chart import Series
# 绘制柱状图
# 创建工作表
ws = wb.create_sheet(
'Bar Chart'
)
# 准备数据
rows = [
(
'Number'
,
'Batch1'
,
'Batch2'
),
(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)
# 绘制柱状图
bar_chart = BarChart()
bar_chart.type =
'col'
# col垂直、水平柱状图 bar
bar_chart.title =
'Bar Chart'
bar_chart.style = 10
# 设置颜色,10的对比度最强,红色与蓝色
# 设置横轴纵轴标题
bar_chart.x_axis.title =
'Sample length(mm)'
bar_chart.y_axis.title =
'Test number'
# 设置分类
category = Reference(ws, min_col=1, min_row=2, max_row=7)
# 获取数据
data = Reference(ws, min_col=2, max_col=3, min_row=1, max_row=7)
# 柱状图对象添加数据
bar_chart.add_data(data, titles_from_data=True)
# titles_from_data=True:根据来源设置数据标题
# 设置分类
bar_chart.set_categories(category)
# 工作页绘制柱状图,并指定位置
ws.add_chart(bar_chart,
'E1'
)
# 保存
wb.save(
'char_excel_text.xlsx'
)