2

I am trying to plot 3 series with 2 on the left y-axis and 1 on the right using secondary_y, but it’s not clear to me how to define the right y-axis scale as I did on the left with ylim=().

I have seen this post: Interact directly with axes

… but once I have:

import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randn(10,3))

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(df.index,df.iloc[:,[0,2]])
ax2.plot(df.index, df.iloc[:,2])

plt.show() doesn't produce anything at all. I am using:

  • Spyder 2.3.5.2
  • python: 3.4.3.final.0
  • python-bits: 64
  • OS: Windows
  • OS-release: 7
  • pandas: 0.16.2
  • numpy: 1.9.2
  • scipy: 0.15.1
  • matplotlib: 1.4.3

What I get for results

I found these links helpful:

tcaswell, working directly with axes

matplotlib.axes documentation

Community
  • 1
  • 1
MJS
  • 1,573
  • 3
  • 17
  • 26

3 Answers3

2

You need to use set_ylim on the appropriate ax.

For example:

ax2 = ax1.twinx()
ax2.set_ylim(bottom=-10, top=10)

Also, reviewing your code, it appears that you are specifying your iloc columns incorrectly. Try:

ax1.plot(df.index, df.iloc[:, :2])  # Columns 0 and 1.
ax2.plot(df.index, df.iloc[:, 2])   # Column 2.
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • hi Alexander - I see the problem with my iloc columns, sorry for that. Can you think of a reason why there would be no repsonse at all? neither plt.show() nor plt.show(ax2) produces any plot. – MJS Nov 30 '15 at 20:26
  • Per your edit, you have the graphic. When you say 'no response', what exactly are you referring to? – Alexander Nov 30 '15 at 20:30
  • good point, poorly worded. i was not able to get a result working only in the console. your corrections to my syntax helped me get back on track. i still have some bad looking plots because the grid lines for the two y axis ticks are off. i will add some other useful links above. thanks for your help. – MJS Nov 30 '15 at 21:29
0
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10,3))
print (df)
fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(df.index,df.iloc[:,[0,2]])
ax2.plot(df.index, df.iloc[:,2])

plt.show()
ctrl-alt-delete
  • 3,696
  • 2
  • 24
  • 37
  • hi toasteez - thanks for responding. I pasted in an image of what I had written above. I must be doing something else wrong. – MJS Nov 30 '15 at 19:55
  • I'm running Anaconda 3.5, from Pycharm nothing displays for me either but if I run from console it plots fine. – ctrl-alt-delete Nov 30 '15 at 20:02
  • I cannot get anything from the iPython console in Anaconda/spyder – MJS Nov 30 '15 at 20:29
0

You can do this without directly calling ax.twinx():

#Plot the first series on the LH y-axis
ax1 = df.plot('x_column','y1_column')

#Add the second series plot, and grab the RH axis
ax2 = df.plot('x_column','y2_column',ax=ax1)
ax2.set_ylim(0,10)

Note: Only tested in Pandas 19.2

user3304496
  • 121
  • 2
  • 6