如何使用 python-pptx 替换现有折线图的数据?

How do you replace data for an existing line chart using python-pptx?

我有一个预建和填充的 powerpoint 演示文稿,我正在修改图表和表格的数据。我想保留所有格式(和大部分文本),但替换幻灯片中折线图中的数据。

我有一个函数可以使用与条形图一起使用的 pandas 数据框替换数据。

def replaceCategoryChart(df, chart, skipLastCol=0):
    """
    Replaces Category chartdata for a simple series chart. e.g. Nonfarm Employment

    Parameters:
    df: dataframe containing new data. column 0 is the categories
    chart: the powerpoint shape chart.
    skipLast: 0=don't skip last column, 1+ will skip that many columns from the end

    Returns: replaced chart(?)
    """
    cols1= list(df)
    #print(cols1)
    #create chart data object
    chart_data = CategoryChartData()
    #create categories
    chart_data.categories=df[cols1[0]]
    # Loop over all series
    for col in cols1[1:-skipLastCol]:
        chart_data.add_series(col, df[col])
    #replace chart data
    chart.replace_data(chart_data)
...
S0_L=  pd.read_excel(EXCEL_BOOK, sheet_name="S0_L", usecols="A:F")
S0_L_chart = prs.slides[0].shapes[3].chart
print(S0_L)
replaceCategoryChart(S0_L, S0_L_chart)
...

python 文件运行成功,但是,当我打开 powerpoint 文件时出现错误

Powerpoint found a problem with content in Name.pptx. 

Powerpoint can attempt to repair the presentation.

If you trust the source of this presentation, click Repair.

点击修复后,我试图修改的幻灯片被一个空白布局所取代。

因为此函数适用于条形图,我认为我理解如何将 replace_data() 用于折线图的方式有误。

感谢您的帮助!

如果您的 "line chart" 是 "XY Scatter" 图表,您将需要一个不同的图表数据对象,即 XyChartData 对象,然后填充其 XySeries 对象: https://python-pptx.readthedocs.io/en/latest/api/chart-data.html#pptx.chart.data.XyChartData

我建议首先使用文字值使其工作,例如"South" 和 1.05,然后继续提供来自 Pandas 数据帧的值。这样您就可以确定代码的 python-pptx 部分结构正确,并且您将知道去哪里寻找出现的任何问题。

正如 scanny 提到的,replace_data() 确实适用于类别折线图。

修复错误(可能)是由于错误添加系列数据引起的,(有一个坏循环,在下面更正)。

    # Loop over all series
    for col in cols1[1:len(cols1)-skipLastCol]:
        print('Type of column is ' + str(type(col)))
        chart_data.add_series(col, df[col])