Openpyxl图表中X轴标签换行技巧
要在openpyxl的图表中换行X轴标签,可以使用'\n'来表示换行。以下是一个示例代码:
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
# 创建Workbook和Sheet
wb = Workbook()
sheet = wb.active
# 添加数据
data = [
['Category', 'Value'],
['Long Label 1\nThis is a long label', 10],
['Long Label 2\nThis is another long label', 20],
['Long Label 3\nThis is yet another long label', 30]
]
for row in data:
sheet.append(row)
# 创建图表
chart = BarChart()
chart.title = "Example Chart"
# 设置X轴标签
categories = Reference(sheet, min_col=1, min_row=2, max_row=sheet.max_row)
chart.x_axis.title = "Category"
chart.x_axis.number_format = 'General'
chart.x_axis.majorTickMark = "none"
# 设置Y轴标签
values = Reference(sheet, min_col=2, min_row=1, max_row=sheet.max_row)
chart.y_axis.title = "Value"
# 添加数据系列
data = Reference(sheet, min_col=2, min_row=2, max_col=2, max_row=sheet.max_row)
series = chart.add_series(data, categories=categories)
chart.series.append(series)
# 将图表添加到Sheet中
sheet.add_chart(chart, "D2")
# 保存Workbook
wb.save("chart.xlsx")
在上面的示例代码中,我们在X轴标签中使用'\n'来换行。请注意,我们还需要设置chart.x_axis.majorTickMark = "none"来隐藏X轴上的刻度线,以便确保标签能够正常显示。
原文地址: https://www.cveoy.top/t/topic/dpmg 著作权归作者所有。请勿转载和采集!