从多列绘制堆叠条形图而不是为每一列绘制图形?

Draw a stacked bar chart from multiple columns instead of drawing a graph for each column?

我有一个包含类似数据列(李克特量表数据)的数据集,我绘制了一个堆叠条形图,分别表示每列的值计数,但如果我想将所有结果合并到一个堆叠条形图中,我该怎么做

我绘制每张图的代码:

def calculate_bar_values(plot,axis):
      for rectangle in plot:
        width = rectangle.get_width()
        axis.text(width+ 0.35, rectangle.get_y() + 0.38, '%d' % int(width),ha='center', va = 'bottom')

df_new =df_responses.iloc[:,9:21] image_format = 'svg' # 例如.png、.svg 等

for col in df_new:
    figure, axis = plt.subplots()
    plot = axis.barh(df_new[col].value_counts().index, df_new[col].value_counts().values )
    #plt.title(col)
    plt.xlabel('Count')
    plt.tight_layout() # to get full text labels when saving the figures
    calculate_bar_values(plot,axis)
    plt.show()
    image_name= col +'.svg'
    figure.savefig(image_name, format=image_format, dpi=1200)

数据集和笔记本可以在这里找到: Dataset + notebook

您的建议将有很大帮助。 谢谢

示例图:

可以通过使用groupby重新排列dataframe来实现。考虑代码:

df_responses= pd.read_csv('https://raw.githubusercontent.com/eng-aomar/Security_in_practice/main/secuirtyInPractice.csv')

df_new =df_responses.iloc[:,9:21]
image_format = 'svg' # e.g .png, .svg, etc.

# initialize empty dataframe
df2 = pd.DataFrame()

# group by each column counting the size of each category values
for col in df_new:
    grped = df_new.groupby(col).size()
    grped = grped.rename(grped.index.name)
    df2 = df2.merge(grped.to_frame(), how='outer', left_index=True, right_index=True)

# plot the merged dataframe
df2.plot.bar(stacked=True)
plt.show()

使用您的数据和笔记本。这是我得到的: