繁体   English   中英

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

[英]how to add xaxis and yaxis label with python-pptx

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

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')

这样的 label 在 PowerPoint 用语中被称为轴标题

您可以使用此处文档中描述的axis.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 之间,您可以控制轴标题文本的颜色、大小、字体等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM