如何使用数据框中的数据向堆叠条形图中的特定列(类别)添加值?

2024-06-30 08:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写代码来执行以下操作:

  • 在数据帧中循环(“问题\数据”)
  • 提取满足特定条件的值(“类别值”)
  • 将这些值添加到列表(“类别值”),然后
  • 使用这些列表作为使用python pptx库的堆叠条形图的系列值。在这一步中,我希望所有项目在条形图中按其类别值(“问题响应”)进行分组

我已经成功地设计了1-3,但不能让4按需要工作;该图表不是使用相同的类别值(“questionresponse”变量)对列表进行分组,而是将系列添加到新的未命名列中,如下所示:

enter image description here

如何根据系列的“问题-回答”值强制将其添加到条形图中的类别中

以下代码注释:问题_数据是从Excel工作表中提取的数据框。它的确切字段和数据与这个问题无关

chart_data = CategoryChartData()
        chart_data.categories = testweek_list
        categoryvalues = []
        for questionresponse in questionresponse_list:
            for test_week in testweek_list:
                categoryvalue = question_data.loc[(question_data['Test Week'] == test_week) & (question_data['Response Option'] == questionresponse), 'Count'].values.astype(int)
                if (categoryvalue != 0) and (categoryvalue != ""):
                    categoryvalues.append(int(categoryvalue))
                    chart_data.add_series(questionresponse, categoryvalues)
        x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
        questionslide.shapes.add_chart(XL_CHART_TYPE.COLUMN_STACKED_100, x, y, cx, cy, chart_data)
        i+=1

下面是期望结果的示例(忽略图中的值,仅用于说明目的):

enter image description here


Tags: 数据代码列表fordatachart类别list