Bar and Column Charts

Bar and Column Charts


柱状图会绘制水平或者垂直的数据列。

Vertical, Horizontal and Stacked Bar Charts

垂直、水平、堆栈柱状图

Note

以下设置将影响不同类型的柱状图。 通过分别设置type的值为bar或col从而使用垂直type=col或水平type=bar柱状图。

当使用堆栈柱状图时,overlap的值需要设置为100。overlap=100

如果是水平柱状图,x和y轴将颠倒。


"Sample bar charts"

  1. from openpyxl import Workbook
  2. from openpyxl.chart import BarChart, Series, Reference
  3. wb = Workbook(write_only=True)
  4. ws = wb.create_sheet()
  5. rows = [
  6. ('Number', 'Batch 1', 'Batch 2'),
  7. (2, 10, 30),
  8. (3, 40, 60),
  9. (4, 50, 70),
  10. (5, 20, 10),
  11. (6, 10, 40),
  12. (7, 50, 30),
  13. ]
  14. for row in rows: # 添加单元格绘图数据
  15. ws.append(row)
  16. chart1 = BarChart() # 创建 2D柱状图 对象
  17. chart1.type = "col" # 柱状图type=col,垂直图。
  18. chart1.style = 10 # style显示不同的风格
  19. chart1.title = "Bar Chart" # 图形名称
  20. chart1.y_axis.title = 'Test number' # y轴名称
  21. chart1.x_axis.title = 'Sample length (mm)' # x名称
  22. data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3) # 关联图形数据
  23. cats = Reference(ws, min_col=1, min_row=2, max_row=7) # 关联数据分类
  24. chart1.add_data(data, titles_from_data=True) # 数据标题从titles_from_data=True获取,即数据单元格组的第一行
  25. chart1.set_categories(cats)
  26. chart1.shape = 4
  27. ws.add_chart(chart1, "A10") # 生成柱状图及定位
  28. from copy import deepcopy
  29. chart2 = deepcopy(chart1) # deepcopy ,之后直接修改部分属性
  30. chart2.style = 11
  31. chart2.type = "bar" # 水平柱状图
  32. chart2.title = "Horizontal Bar Chart"
  33. ws.add_chart(chart2, "G10") # 生成柱状图及定位
  34. chart3 = deepcopy(chart1) # deepcopy ,之后直接修改部分属性
  35. chart3.type = "col" # 水平柱状图
  36. chart3.style = 12
  37. chart3.grouping = "stacked" # 类型为堆栈
  38. chart3.overlap = 100 # 必须设置内容
  39. chart3.title = 'Stacked Chart'
  40. ws.add_chart(chart3, "A27") # 生成柱状图及定位
  41. chart4 = deepcopy(chart1)
  42. chart4.type = "bar" # 水平柱状图
  43. chart4.style = 13
  44. chart4.grouping = "percentStacked" # 类型 百分比堆栈
  45. chart4.overlap = 100
  46. chart4.title = 'Percent Stacked Chart'
  47. ws.add_chart(chart4, "G27")
  48. wb.save("bar.xlsx")

这样便生成了4种不同类型的柱状图。

3D Bar Charts

3D柱状图

可以生成3D柱状图。

  1. from openpyxl import Workbook
  2. from openpyxl.chart import (
  3. Reference,
  4. Series,
  5. BarChart3D,
  6. )
  7. wb = Workbook()
  8. ws = wb.active
  9. rows = [
  10. (None, 2013, 2014),
  11. ("Apples", 5, 4),
  12. ("Oranges", 6, 2),
  13. ("Pears", 8, 3)
  14. ]
  15. for row in rows:
  16. ws.append(row)
  17. data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=4)
  18. titles = Reference(ws, min_col=1, min_row=2, max_row=4)
  19. chart = BarChart3D() # 创建 3D柱状图 对象
  20. chart.title = "3D Bar Chart"
  21. chart.add_data(data=data, titles_from_data=True)
  22. chart.set_categories(titles)
  23. ws.add_chart(chart, "E5")
  24. wb.save("bar3d.xlsx")

如此便生成了一个简单的 3D柱状图

"Sample 3D bar chart"


^ <-Previous | Next-> |