如何使用 python-pptx 添加 xaxis 和 yaxis 标签

how to add xaxis and yaxis label with python-pptx

我正在学习python-pptx。我有下面的简单示例,它生成折线图并且工作正常。如何将 xaxis 标签即 "Quarters" 和 yaxis 标签添加为 "Sales" 到此图表?

from pptx import Presentation
from pptx.util import Inches
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE

# create presentation with 1 slide ------
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])

# define chart data ---------------------
chart_data = ChartData()
chart_data.categories = ['Q1 Sales', 'Q2 Sales', 'Q3 Sales']
chart_data.add_series('West',    (32.2, 28.4, 34.7))
chart_data.add_series('East',    (24.3, 30.6, 20.2))
chart_data.add_series('Midwest', (20.4, 18.3, 26.2))

x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
    XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data
).chart

chart.has_legend = True
chart.legend.include_in_layout = False
chart.series[0].smooth = True
prs.save('test1.pptx')

这样的标签在 PowerPoint 中称为 轴标题

您可以使用此处文档中描述的 axis.axis_title 属性 访问轴的 axis-title object:
https://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.axis._BaseAxis.axis_title

所以像这样的东西应该可以解决你的问题:

category_axis_title = chart.category_axis.axis_title
category_axis_title.text_frame.text = "Quarter"
value_axis_title = chart.value_axis.axis_title
value_axis_title.text_frame.text = "Sales"

TextFrame object 和 ChartFormat object 之间,与 axis-title 相关联,您可以控制颜色、大小、字体等axis-title 文本。