Pandas: Plotting secondary axis

Created on 19 Jan 2015  路  5Comments  路  Source: pandas-dev/pandas

This could be either a bug, or an error in the documentation, or just my fault (hopefully the third reason).

Pandas 0.15.2 documentation explains how to create one plot with two axes (http://pandas.pydata.org/pandas-docs/dev/visualization.html?highlight=visualization#plotting-on-a-secondary-y-axis). For example:

import numpy as np,pandas as pd,matplotlib.pyplot as plt
x=pd.DataFrame(range(100))**.5
y=x+np.random.normal(size=(x.shape[0],1))

# Does not work ()
x.plot()
y.plot(secondary_y=True,style='g:')
plt.show()

The problem is, two plots are generated, rather than only one with two axes.

This alternative would work:

# Works (1 figure, 2 axes)
fig,ax=plt.subplots()
ax2=ax.twinx()
x.plot(ax=ax)
y.plot(ax=ax2,style='g:')
plt.show()

Question: Does the example in the documentation actually generate a plot with 2 axes? What I get is two separate plots. This seems to be a bug. If this is not a bug, then I would suggest the example in the documentation is modified to explain the second alternative.

Visualization

Most helpful comment

@TomAugspurger, indeed, that's a nice workaround. I think the documentation could make that clear. The example presented only works for series, and the documentation does not specifically exclude dataframes.

Thanks for the hint!!

All 5 comments

Hmm, those examples are plotting Series.

Your code works if you do y[0].plot(secondary_y=True). I'd need to think about whether this should work for DataFrames (my initial reaction is that it should).

Thank you, @TomAugspurger. I also think it should work for dataframes. The documentation makes no distinction, and why to limit the plot functionality anyway...

I guess the real solution is to catch the axes that's returned in the first plot and pass that into the second.

In [33]: ax = x.plot()

In [34]: y.plot(secondary_y=True,style='g:', ax=ax)
Out[34]: <matplotlib.axes._subplots.AxesSubplot at 0x10086630>

This will work for multiple columns.

If you don't mind, I'm going to close this issue, since it's going to be "fixed" by however we handle #8776. If you haven't looked at that issue, it's about how Series.plot() plots on the currently active axis, while DataFrame.plot() plots on a new one.

@TomAugspurger, indeed, that's a nice workaround. I think the documentation could make that clear. The example presented only works for series, and the documentation does not specifically exclude dataframes.

Thanks for the hint!!

Was this page helpful?
0 / 5 - 0 ratings