Home > OS >  adding mean line and data label to a pandas' plot
adding mean line and data label to a pandas' plot

Time:02-11

I plotted a series of subplots of a Dataframe's columns, and I cannot find a way to add data labels and a mean line to the plots.

my code now looks something like this (I'm simplifying the data here):

categorized = pd.DataFrame(data={"food":[50, 60, 23, 80], 
                                 "books":[10, 18, 3, 12], 
                                 "cloths":[30, 50, 23, 80]},
                           index=["jan", "feb", "mar", "apr"])
a = categorized.plot(kind='bar', subplots=True, legend=False, figsize=(25, 105), sharex=False, layout=(4, 1))
plt.subplots_adjust(hspace=0.55)

I found two ways to handle this but I can't use any of them:

  1. to use matplotlib, which has the option of mean and data labels - but I didn't see an option for multiple subplots (one per column)
  2. pandas' above example - with subplots - but I couldn't find how to add data labels and mean line

Is there another way that combines the benefits of both options? Thanks!

CodePudding user response:

I'm not sure what you're trying to do as far as subplots, data labels, and the mean line go, but here is a script that produces a result similar to the result of the pandas command. In particular, it produces a plot with the three bar graphs as subplots, stacked on top of each other. Unlike the pandas command, the bars here are a bit wider and the colors are the same.

categorized = pd.DataFrame(data={"food":[50, 60, 23, 80], 
                                 "books":[10, 18, 3, 12], 
                                 "cloths":[30, 50, 23, 80]},
                           index=["jan", "feb", "mar", "apr"])
fig,axs = plt.subplots(3,sharex = False, figsize=(10, 42))

for k,c in enumerate(categorized.columns):
    axs[k].bar(categorized.index,categorized.loc[:,c])
    axs[k].set_title(c)

Result:

enter image description here

Pandas result for comparison:

enter image description here

  • Related