有没有办法在图表中 "Switch row/column" 数据?

Is there a way to "Switch row/column" data in a chart?

我正在创建一个图表,想在 PowerPoint 中打开图表之前切换我输入的数据的行和列。该系列的格式和分组不正确,图表在这种情况下毫无意义。

我正在使用元组,据我所知这很难操作,所以如果我缺少一个命令只需切换 rows/columns?这似乎是最简单的解决方案。

x3 = Inches(0.3)
y3 = Inches(3.7)
cx3 = Inches(1.25)
cy3 = Inches(1.25)

chart_data_marriage = CategoryChartData()
chart_data_marriage.categories = ['Married HH', 'Married Footprint']

demographics['Profile List Title'] = demographics['Profile List Title'].str.strip()

tuple_married1 = demographics['Family Renters : Users/100 HHs']
tuple_married_footprint = demographics['Profile List: Total Profile Users/100 HHs']


tuple_married1.drop([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95], inplace = True)

tuple_married_footprint.drop([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95], inplace = True)

chart_data_marriage.add_series('Family Renters : Users/100 HHs', (tuple_married1))
chart_data_marriage.add_series('Profile List: Total Profile Users/100 HHs', (tuple_married_footprint))

marriagechart = storyboard1.shapes.add_chart(XL_CHART_TYPE.DOUGHNUT, x3, y3, cx3, cy3, chart_data_marriage).chart
marriagechart.has_legend = False

tuple_married1tuple_married_footprint 中,我都有创建圆环图所需的数据,因此只需按正确的顺序格式化系列即可。同样,像现在存在于 PowerPoint 中的按钮这样的切换行和列命令将是理想的,否则可能需要更复杂的解决方案。

python-pptx 没有 "pivot-chart-data" 行为,但它很容易完成并且是一个有趣的谜题。

如果您以正确的形式插入您的值(与您提供给 ChartData 的形式几乎相同),这样的事情应该可以解决问题,您当然可以调整它以适应:

original_cats = ("a", "b", "c")
original_sers = (
    ("Series 1", (1, 2, 3)),
    ("Series 2", (4, 5, 6)),
)

new_cats = tuple(ser[0] for ser in original_sers)
# --> ("Series 1", "Series 2")

new_sers = tuple(
    (original_cats[i], (s[1][i] for s in original_sers))
    for i in range(len(original_cats))
)
# --> (("a", (1, 4)), ("b", (2, 5)), ("c", (3, 6)))

如果您的数据来自 Pandas 数据框,您可以在将数据移动到 pptx 之前执行 demographics.T