3

I have this dataframe :

    Count Actual_Rate Exp_Rate  right2
0   122  4.002625    2.265885   0.05
1   136  9.523810    7.243974   0.10
2   128  14.253898   12.321206  0.15
3   79   15.280464   17.353428  0.20
4   70   19.607843   22.253587  0.25
5   56   23.628692   27.285757  0.30
6   38   25.675676   32.166862  0.35
7   34   25.954198   37.089576  0.40
8   24   34.285714   42.326437  0.45
9   16   33.333333   47.542286  0.50
10  15   45.454545   52.818506  0.55
11  7    35.000000   57.273622  0.60
12  10   41.666667   62.536824  0.65
13  6    33.333333   66.974825  0.70
14  7    53.846154   72.128450  0.75
15  6    66.666667   77.230268  0.80
16  8    66.666667   82.263247  0.85
17  2    100.000000  87.485802  0.90
18  3    100.000000  92.918269  0.95

I'm trying to build an overlayed plot consisting of two lines of Actual_Rate and Exp_Rate and a bar plot of Count, using right2 as x-ticks.

This was my attempt:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df.plot(kind='bar',x='right2',y='Count', ax=ax1)

ax2.plot(df['right2'],df['Actual_Rate'],color="r")
ax2.plot(df['right2'],df['Exp_Rate'],color="g")
ax2.set_xticklabels(labels = df['right2'])
plt.show()

But the result was unsuccessful (unfortunately for some reason I am unable to upload the image, but I will try to do it after the question is posted).

amestrian
  • 546
  • 3
  • 12
  • A pandas bar plot always creates a categorical x-axis, internally numbered `0,1,2,...`. You could try `ax2.plot((df['right2']-0.05)/0.05, df['Actual_Rate'])` to plot the lines at the same spots. – JohanC Dec 16 '21 at 15:37
  • @JohanC the duplicate link (or your solution) does not respect the numeric scale of `right2`. In this case, it may not be important as the data is evenly spaced anyway. – Quang Hoang Dec 16 '21 at 15:45
  • One of the linked dupes surely uses `ax.bar` instead of `df.plot(kind='bar', ...)`. With `ax2.plot((df['right2']-0.05)/0.05, df['Actual_Rate'])` you still can use `ax2.set_xticklabels(df['right2'])`. In this specific case, `ax.bar` is indeed the better solution. The dupes show alternatives for many situations. – JohanC Dec 16 '21 at 15:52

0 Answers0