0

I have pandas df as below.

df:

   vl  ma  fg
0   5  20   1
1   6  20   2
2   2  20   3
3   4  30   1
4   9  30   2
5   6  30   3
6  32  40   1
7   7  40   2
8   5  40   3

I have grouped and averaged by "ma":

df2:

   ma         vl   fg
0  20   4.333333  2.0
1  30   6.333333  2.0
2  40  14.666667  2.0

I'd like to plot the mean value df2 as a bar chart, but have the upper and lower levels for "ma" column shown on the bar from df dataframe, something like this:

enter image description here

import pandas as pd
import matplotlib.pyplot as plt

data={"vl": [5,6,2,4,9,6,32,7,5],
            "ma": [20,20,20,30,30,30,40,40,40],
            "fg": [1,2,3,1,2,3,1,2,3]}

df = pd.DataFrame(data)
df2 =df.groupby("ma", as_index=False).mean()

plt.bar(df2.ma, df2.vl)
plt.show()
Sylv99
  • 151
  • 8
  • plt.vlines(x=20,ymin=2,ymax=6) plt.hlines(y=[2,6],xmin=19,xmax=21) – Ran A Mar 29 '22 at 08:36
  • Thank you. Is there a way to do this for all "ma" values in df2? - 20, 30 and 40 – Sylv99 Mar 29 '22 at 08:58
  • yes you can add as many as you want, example for ma 40 ,plt.vlines(x=40,ymin=7,ymax=32) plt.hlines(y=[7,32],xmin=39,xmax=41) – Ran A Mar 29 '22 at 09:16

0 Answers0