Search code examples
python-3.xpython-pptx

How to update the date range on X-Axis with python-pptx


I have a multi-line chart that I'm trying to update the data for. I can change the data for the data series (1 to 5) in my case using a dataframe; I'm unable to figure out how to change the range for the category axis. In the current scenario, I have the daterange starting from 2010; I can't figure out how to update that dynamically bases on input data

My chart is as shown below: Powerpoint Chart

My chart data is as below: Powerpoint chart data

My code is as below:

import pandas as pd
from pptx import Presentation
from pptx.chart.data import CategoryChartData, ChartData

df = pd.DataFrame({
    'Date':['2010-01-01','2010-02-01','2010-03-01','2010-04-01','2010-05-01'],
    'Series 1': [0.262918, 0.259484,0.263314,0.262108,0.252113],
    'Series 2': [0.372340,0.368741,0.375740,0.386040,0.388732],
    'Series 3': [0.109422,0.109256,0.112426,0.123932,0.136620],
    'Series 4': [0.109422,0.109256,0.112426,0.123932,0.136620], # copy of series 3 for easy testing
    'Series 5': [0.109422,0.109256,0.112426,0.123932,0.136620], # copy of series 3 for easy testing
})
prs = Presentation(presentation_path)    
   
def update_multiline(chart,df):
    plot = chart.plots[0]
    category_labels = [c.label for c in plot.categories]
    # series = plot.series[0]
    chart_data = CategoryChartData()
    chart_data.categories = [c.label for c in plot.categories]


    category_axis = chart.category_axis
    category_axis.minimum_scale = 1 # this should be a date
    category_axis.minimum_scale = 100 # this should be a date
    tick_labels = category_axis.tick_labels
    df = df.drop(columns=['Date'])

    for index in range(df.shape[1]):
        columnSeriesObj = df.iloc[:, index]
        chart_data.add_series(plot.series[index].name, columnSeriesObj)
    chart.replace_data(chart_data)

# ================================ slide index 3 =============================================

slide_3 = prs.slides[3]
slide_3_title = slide_3.shapes.title # assigning a title

graphic_frame = slide_3.shapes
# slide has only one chart and that's the 3rd shape, hence graphic_frame[2]
slide_3_chart = graphic_frame[2].chart
update_multiline(slide_3_chart, df)

prs.save(output_path)

How to update the date range if my date in the dataframe starts from say 2015 i.e. 'Date':['2015-01-01','2015-02-01','2015-03-01','2015-04-01','2015-05-01']


Solution

  • You are simply copying the categories of the old chart into the new chart with:

    chart_data.categories = [c.label for c in plot.categories]
    

    You must draw the category labels from the dataframe if you expect them to change.