Issue
I'm looking to create a single horizontal stacked bar chart as an alternative to a pie chart to show percentages.
I'm pretty sure plot.barh will do the job (it creates multiple stacked bars in another piece of code I have). But here it doesn't stack the bars. How do I fix it?
import pandas as pd
import matplotlib.pyplot as plt
data=pd.DataFrame(data={"R1":["Yes","Yes","Yes","No","No"]})
freq = data["R1"].value_counts(normalize=True)*100
fig,ax = plt.subplots()
freq.plot.barh(ax=ax,stacked=True)
Solution
Stacking means putting several series of one dataframe on top of each other, so their values cumulate.
You have a single series only, with two values, which consequently are plotted in one bar series.
You could make a DataFrame out of your series, transform it so that Yes
and No
are two columns with one value each and then plot it the way you tried:
freq.to_frame().T.plot.barh(stacked=True)
to examine the difference:
freq
# Yes 60.0
# No 40.0
# Name: R1, dtype: float64
freq.to_frame().T
# Yes No
# R1 60.0 40.0
Answered By - SpghttCd
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.