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

Time:03-09

I have a dataset that contained similar data columns (Likert scale data), I drew a stacked bar that represents the value counts for each column separately, but if I want to combine all the results in one stacked bar graph, how can I do that

my code for drawing each graph:

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' # e.g .png, .svg, etc.

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)

The dataset and the notebook can be found here : bar chart

CodePudding user response:

It can be achieved by rearranging the dataframe using groupby. Consider the code:

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()

Using your data and notebook. This is what I get:

Stacked Bar Plot

  • Related