pin_drop当前位置:知识文库 ❯ 图文
openpyxl创建Excel图表详解 - 柱状图折线图饼图制作教程
图表功能概述
openpyxl支持在Excel中创建多种图表,包括柱状图、折线图、饼图、散点图、面积图等。图表通过引用工作表中的数据区域生成,可以设置标题、图例、坐标轴、样式等属性。创建图表后添加到工作表中,在Excel中打开即可看到可视化效果。
图表是数据可视化的重要工具,能够让数据更加直观和易于理解。在Excel报表中嵌入图表,可以帮助读者快速识别数据趋势、比较不同类别的差异、分析占比分布等。
语法与参数说明
基本语法
代码示例
from openpyxl.chart import BarChart, LineChart, PieChart, Reference
chart = BarChart()
data = Reference(ws, min_col, min_row, max_col, max_row)
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
ws.add_chart(chart, 'A10')Reference参数说明
Chart常用属性
支持的图表类型
返回值说明
add_chart()方法无返回值,图表直接添加到工作表的指定位置(由单元格坐标确定)。图表数据会随源数据的变化而更新,在Excel中打开即可看到渲染效果。
代码示例详解
示例1:柱状图
演示如何创建一个展示季度销售与利润对比的柱状图:
代码示例
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
wb = Workbook()
ws = wb.active
# 写入数据
ws.append(['季度', '销售额', '利润'])
ws.append(['Q1', 120, 30])
ws.append(['Q2', 150, 45])
ws.append(['Q3', 180, 55])
ws.append(['Q4', 200, 60])
# 创建柱状图
chart = BarChart()
chart.title = '季度销售与利润'
chart.style = 10
chart.x_axis.title = '季度'
chart.y_axis.title = '金额(万元)'
chart.width = 15
chart.height = 10
# 添加数据
data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=5)
cats = Reference(ws, min_col=1, min_row=2, max_row=5)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
# 添加图表到工作表
ws.add_chart(chart, 'A7')
wb.save('chart_bar.xlsx')
print("柱状图文件已保存")输出结果:
代码示例
柱状图文件已保存示例2:折线图与饼图
在同一工作簿中创建折线图(展示趋势)和饼图(展示占比):
代码示例
from openpyxl import Workbook
from openpyxl.chart import LineChart, PieChart, Reference
wb = Workbook()
# 折线图工作表
ws1 = wb.active
ws1.title = '趋势'
ws1.append(['月份', '用户数', '收入'])
months = ['1月', '2月', '3月', '4月', '5月', '6月']
users = [1000, 1200, 1500, 1800, 2200, 2800]
revenue = [50, 60, 75, 90, 110, 140]
for i, m in enumerate(months):
ws1.append([m, users[i], revenue[i]])
# 创建折线图
line_chart = LineChart()
line_chart.title = '用户增长趋势'
line_chart.style = 10
line_chart.x_axis.title = '月份'
line_chart.y_axis.title = '数量'
line_chart.width = 18
line_chart.height = 10
data = Reference(ws1, min_col=2, min_row=1, max_col=3, max_row=7)
cats = Reference(ws1, min_col=1, min_row=2, max_row=7)
line_chart.add_data(data, titles_from_data=True)
line_chart.set_categories(cats)
ws1.add_chart(line_chart, 'A9')
# 饼图工作表
ws2 = wb.create_sheet('占比')
ws2.append(['渠道', '占比'])
ws2.append(['直接访问', 30])
ws2.append(['搜索引擎', 25])
ws2.append(['社交媒体', 20])
ws2.append(['邮件推广', 15])
ws2.append(['其他', 10])
pie_chart = PieChart()
pie_chart.title = '流量来源占比'
pie_chart.style = 10
data = Reference(ws2, min_col=2, min_row=1, max_row=6)
cats = Reference(ws2, min_col=1, min_row=2, max_row=6)
pie_chart.add_data(data, titles_from_data=True)
pie_chart.set_categories(cats)
ws2.add_chart(pie_chart, 'A8')
wb.save('chart_line_pie.xlsx')
print("折线图与饼图文件已保存")输出结果:
代码示例
折线图与饼图文件已保存示例3:多系列图表与样式
创建包含多个数据系列的柱状图,并添加数据标签:
代码示例
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.chart.series import DataPoint
from openpyxl.chart.label import DataLabelList
wb = Workbook()
ws = wb.active
# 写入数据
ws.append(['产品', '1月', '2月', '3月'])
ws.append(['产品A', 100, 120, 150])
ws.append(['产品B', 80, 95, 110])
ws.append(['产品C', 60, 75, 90])
# 创建图表
chart = BarChart()
chart.type = 'col' # 'col'柱状, 'bar'条形
chart.title = '产品月度销售对比'
chart.style = 10
chart.x_axis.title = '产品'
chart.y_axis.title = '销量'
data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=4)
cats = Reference(ws, min_col=1, min_row=2, max_row=4)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
# 设置数据标签
chart.dataLabels = DataLabelList()
chart.dataLabels.showVal = True
# 图表尺寸
chart.width = 18
chart.height = 12
ws.add_chart(chart, 'A6')
wb.save('chart_multi_series.xlsx')
print("多系列图表文件已保存")输出结果:
代码示例
多系列图表文件已保存实际应用场景
-
销售报表:使用柱状图对比各月或各季度的销售额、利润等指标
-
趋势分析:使用折线图展示用户增长、访问量变化、收入趋势等时间序列数据
-
构成分析:使用饼图展示各渠道占比、部门预算分配、市场份额等
注意事项与图表对比
注意:图表数据引用使用Reference对象,行列索引从1开始,不是从0开始。
注意:
titles_from_data=True时,第一行数据会作为系列名称使用。
注意:图表在openpyxl中无法渲染预览,需要在Excel中打开查看最终效果。
图表类型对比
小贴士
BarChart的type属性可以设置为'col'(垂直柱状)或'bar'(水平条形)。设置chart.dataLabels.showVal = True可以在柱子上显示具体数值。饼图默认显示图例,可通过chart.legend = None隐藏图例。
小结与练习题
小结
-
Reference定义数据引用区域,Chart对象定义图表类型和样式
-
add_data()添加数据系列,set_categories()设置分类标签
-
BarChart、LineChart、PieChart是最常用的三种图表类型
-
图表需在Excel中查看效果,openpyxl无法预览渲染
练习题
练习1
创建一个包含4个季度销售数据的柱状图,设置标题、X轴和Y轴标签。
练习2
创建一个包含6个月用户数据的折线图,展示增长趋势,图表宽度设为18厘米。
练习3
创建一个饼图,展示5个部门的预算占比,添加数据标签显示具体数值。
常见问题
如何在同一个图表中添加多个数据系列?
只需让Reference对象的数据区域包含多列数据即可。例如min_col=2, max_col=4会引用第2到第4列作为3个数据系列。openpyxl会自动将每一列识别为一个系列。
chart.style的取值范围是什么?
chart.style的取值范围是1到48,每个数字对应Excel中的一种预设样式,影响图表的颜色主题和视觉效果。推荐使用style=10(较现代的配色方案)。
如何调整图表在Excel中的位置?
使用ws.add_chart(chart, 'A10')的第二个参数指定图表左上角所在的单元格坐标。例如'A10'表示图表从第10行A列开始放置,'C5'表示从第5行C列开始。
如何在饼图中显示百分比?
可以通过为每个系列设置dataLabels来显示百分比:from openpyxl.chart.series import DataPoint; from openpyxl.chart.label import DataLabelList。然后设置pie_chart.dataLabels = DataLabelList()和pie_chart.dataLabels.showPercent = True。
散点图的数据格式与柱状图有什么不同?
散点图需要两组数值(X值和Y值),使用ScatterChart和相应的Series对象来设置xValues和yValues。而柱状图使用set_categories()设置分类标签,用add_data()添加数值系列。
本文涉及AI创作
内容由AI创作,请仔细甄别