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?

2
  • 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. Commented Feb 28, 2019 at 15:05
  • I can't reproduce the behavior shown, can you post the code you used to create the first plot? Commented Feb 28, 2019 at 18:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.