简体   繁体   中英

how to add xaxis and yaxis label with python-pptx

I am learning python-pptx. I have simple below example which generate line chart and is working fine. How can I add xaxis label ie"Quarters" and yaxis label as "Sales" to this chart?

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

Such a label is known as an axis title in PowerPoint parlance.

You can access the axis-title object for an axis using the axis.axis_title property described in the documentation here:
https://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.axis._BaseAxis.axis_title

So something like this should do the trick in your case:

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"

Between the TextFrame object and ChartFormat object associated with the axis-title you have control over the color, size, font, etc. of the axis-title text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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