在条形图中,值以水平条或垂直列的形式展示。
垂直、水平和堆叠条形图¶
下列设置影响不同的图表类型:
1. 通过“type”设置为“col”或“bar”,在垂直条形图和水平条形图之间切换。
2. 使用堆叠图表时,需要将overlap设置为100。
3. 如果条是水平的,则x轴和y轴是相反的。
1 from openpyxl import Workbook
2 from openpyxl.chart import BarChart, Series, Reference
3
4 wb = Workbook(write_only=True)
5 ws = wb.create_sheet()
6
7 rows = [
8 ('Number', 'Batch 1', 'Batch 2'),
9 (2, 10, 30),
10 (3, 40, 60),
11 (4, 50, 70),
12 (5, 20, 10),
13 (6, 10, 40),
14 (7, 50, 30),
15 ]
16
17
18 for row in rows:
19 ws.append(row)
20
21
22 chart1 = BarChart()
23 chart1.type = "col"
24 chart1.style = 10
25 chart1.title = "Bar Chart"
26 chart1.y_axis.title = 'Test number'
27 chart1.x_axis.title = 'Sample length (mm)'
28
29 data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
30 cats = Reference(ws, min_col=1, min_row=2, max_row=7)
31 chart1.add_data(data, titles_from_data=True)
32 chart1.set_categories(cats)
33 chart1.shape = 4
34 ws.add_chart(chart1, "A10")
35
36 from copy import deepcopy
37
38 chart2 = deepcopy(chart1)
39 chart2.style = 11
40 chart2.type = "bar"
41 chart2.title = "Horizontal Bar Chart"
42
43 ws.add_chart(chart2, "G10")
44
45
46 chart3 = deepcopy(chart1)
47 chart3.type = "col"
48 chart3.style = 12
49 chart3.grouping = "stacked"
50 chart3.overlap = 100
51 chart3.title = 'Stacked Chart'
52
53 ws.add_chart(chart3, "A27")
54
55
56 chart4 = deepcopy(chart1)
57 chart4.type = "bar"
58 chart4.style = 13
59 chart4.grouping = "percentStacked"
60 chart4.overlap = 100
61 chart4.title = 'Percent Stacked Chart'
62
63 ws.add_chart(chart4, "G27")
64
65 wb.save("bar.xlsx")
三维条形图¶
也可以创建三维条形图
1 from openpyxl import Workbook
2 from openpyxl.chart import (
3 Reference,
4 Series,
5 BarChart3D,
6 )
7
8 wb = Workbook()
9 ws = wb.active
10
11 rows = [
12 (None, 2013, 2014),
13 ("Apples", 5, 4),
14 ("Oranges", 6, 2),
15 ("Pears", 8, 3)
16 ]
17
18 for row in rows:
19 ws.append(row)
20
21 data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=4)
22 titles = Reference(ws, min_col=1, min_row=2, max_row=4)
23 chart = BarChart3D()
24 chart.title = "3D Bar Chart"
25 chart.add_data(data=data, titles_from_data=True)
26 chart.set_categories(titles)
27
28 ws.add_chart(chart, "E5")
29 wb.save("bar3d.xlsx")
这将生成一个简单的三维条形图。