问题:
计划用openpyxl将buy_mount这一列数据设为柱状图的横坐标,但是现在的横坐标是错误的,我应该怎么改。
同时,饼状图显示的数据的标注不全(只能显示0-8),怎样改才能显示全。
求指点。
代码:
import os
import time
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.chart import PieChart, Reference
# BarChart
def drawBarchart(ws, lenrows):
chart = BarChart()
chart.type = "col"
chart.style = 10
chart.title = "柱状图"
chart.y_axis.title = 'Data'
chart.x_axis.title = 'Buy mount'
data = Reference(ws, min_col=2, min_row=2, max_row=1+lenrows, max_col=2)
cats = Reference(ws, min_col=1, min_row=2, max_row=1+lenrows)
chart.set_categories(cats)
chart.add_data(data, titles_from_data=True)
ws.add_chart(chart, "D1")
return 0
# PieChart
def drawPiechart(ws, lenrows):
pie = PieChart()
pie.style = 10
pie.title = "饼状图"
labels = Reference(ws, min_col=1, min_row=2, max_row=1+lenrows)
data = Reference(ws, min_col=2, min_row=2, max_row=1+lenrows, max_col=2)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
ws.add_chart(pie, "D20")
return 0
if __name__ == "__main__":
time_start = time.perf_counter()
print("Path:", os.getcwd())
tableName = "./charts.xlsx"
wb = load_workbook(tableName)
sheet = wb.active
lensheet = sheet.max_row
drawBarchart(sheet, lensheet)
drawPiechart(sheet, lensheet)
# 保存表格
wb.save(tableName)
time_end = time.perf_counter()
print("Speed Times:{:.4f} s".format(time_end-time_start))