0

I need to do a plot using three variables. One of them should be on the secondary Y axis in bar format (kind), the remaining variables (two) should be on the left axis using a simple line. However, I got the following chart:

enter image description here

When I use the three variables in line format I get the right plot (which is not very useful for a visual analysis): enter image description here

I did a quick test using a small sample from my data (code below). I get the right pic when I use bar format for the third one. enter image description here

I wonder, what is going on? Is there a problem with the data size (which I dont think so bcs I get less than 100 rows)?

df2 = pd.DataFrame({'ind':[120.29, 125.45, 127.37, 130.39, 128.30], 
                    'var1':[129.907990, 129.571185, 129.234380, 128.897574, 128.560769], 
                    'var2':[-0.074037, -0.031806, -0.014426, 0.011578, -0.002028]})

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df2['ind'].plot(ax=ax1)
df2['var1'].plot(ax=ax1)
df2['var2'].plot(kind='bar', ax=ax2, color='r')
plt.show()

PD: In addition, I noted that in the third pic the line is behind the bar. How can I change that?

Newbie
  • 451
  • 1
  • 3
  • 14
  • A pandas bar plot is a categorical plot; you get one tick and label per bar. I suppose you can google for something like "pandas plot line and bar in same chart" or so to find an appropriate duplicate Q&A. – ImportanceOfBeingErnest Feb 28 '19 at 15:05
  • I can't reproduce the behavior shown, can you post the code you used to create the first plot? – William Miller Feb 28 '19 at 18:32

1 Answers1

1

I found the solution for this (this link helped me a lot ). Basically, it is based on the index you set up previously.

This is the new code:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df2.index, df2['ind']) 
ax1.plot(df2.index, df2['var1'])
ax2.bar(df2.index, df2['var2'], color='r')
plt.show()

Hope this helps.

Newbie
  • 451
  • 1
  • 3
  • 14