
如圖,下面的柱形圖就是基于上面的圖表生成的
CreateBarChart.py
import os
import sys
from openpyxl import load_workbook
from openpyxl import chart
from openpyxl.chart import BarChart, Reference
from openpyxl.chart.series import SeriesLabel
from openpyxl.drawing.text import ParagraphProperties, CharacterProperties
def set_chart_title_size(chart, size=1400):
'''設(shè)置chart的title的字號'''
paraprops = ParagraphProperties()
paraprops.defRPr = CharacterProperties(sz=size)
for para in chart.title.tx.rich.paragraphs:
para.pPr=paraprops
def get_cur_dir():
'''獲取當前py文件所在目錄'''
dirPath = os.path.dirname(sys.argv[0])
return dirPath
if __name__ == "__main__":
'''創(chuàng)建柱形圖'''
wbPath = os.path.join(get_cur_dir(),'科室同疾病.xlsx')
wb = load_workbook(wbPath, data_only=False)
wsName = '測試'
ws = wb[wsName]
# 每個x的單位中有幾類值,這幾類值的名字、(柱子的)顏色分別是什么
SeriesCnt = 2
SeriesTitles = ['均次費用 2024年','均次費用 2025年']
SeriesColors = ['5B9BD5','ED7D31']
# 3、4是本組的category(x軸標簽),5、6是具體數(shù)據(jù)
categories = Reference(ws, min_col=3, max_col=4, min_row=4, max_row=11)
values = Reference(ws , min_col=5, max_col =6, min_row=4, max_row=11)
# 創(chuàng)建柱形圖
curChart = BarChart()
# 設(shè)置標題:內(nèi)容、字號
curChart.title = '柱形圖名稱'
set_chart_title_size(curChart, size=1500)
# 圖的左上角從哪個單元格開始
beginRow = 15
curChart.anchor = f'A{beginRow}'
# 柱形圖高度
curChart.height = 10
# 柱形圖寬度
curChart.width = 20
# 每個x的單位中的幾類值(柱子)之間的重疊程度(負數(shù)表示不重疊且有間隔)
curChart.overlap = -20
# 一行對應(yīng)一組(Category)數(shù)據(jù)
curChart.add_data(values, from_rows=False)
curChart.set_categories(categories)
# series(各類柱子)的說明顯示在上下左右哪個位置:'b', 'tr'(右上 top right), 'l', 'r', 't'
curChart.legend.position = 'b'
# 防止標簽和柱形圖本體(柱子下方的說明)重疊
curChart.legend.overlay = False
# 設(shè)置各series說明的內(nèi)容和各series的顏色
for i in range(SeriesCnt):
curChart.series[i].title =SeriesLabel(v=SeriesTitles[i])
curChart.series[i].graphicalProperties.solidFill = SeriesColors[i]
# 每個柱子上方顯示且只顯示數(shù)值
curChart.dLbls=chart.label.DataLabelList()
curChart.dLbls.showSerName = False
curChart.dLbls.showCatName = False
curChart.dLbls.showLegendKey = False
curChart.dLbls.showVal = True
# 顯示x、y軸的刻度
curChart.x_axis.delete = False
curChart.y_axis.delete = False
# 把畫好的柱形圖設(shè)置到sheet中:
ws.add_chart(curChart)
# 保存
wb.save(wbPath)
wb.close()
print('生成了柱形圖!')