Skip to content Skip to sidebar Skip to footer

Secondary_y=true Changes X Axis In Pandas

I'm trying to plot two series together in Pandas, from different dataframes. Both their axis are datetime objects, so they can be plotted together: amazon_prices.Close.plot() dat

Solution 1:

import matplotlib.pyplotas plt
import pandas as pd
from numpy.randomimport random

df = pd.DataFrame(random((15,2)),columns=['a','b'])
df.a = df.a*100

fig, ax1 = plt.subplots(1,1)
df.a.plot(ax=ax1, color='blue', label='a')
ax2 = ax1.twinx()
df.b.plot(ax=ax2, color='green', label='b')
ax1.set_ylabel('a')
ax2.set_ylabel('b')
ax1.legend(loc=3)
ax2.legend(loc=0)
plt.show()

enter image description here

Solution 2:

I had the same issue, always getting a strange plot when I wanted a secondary_y.

I don't know why no-one mentioned this method in this post, but here's how I got it to work, using the same example as cphlewis:

import matplotlib.pyplotas plt
import pandas as pd
from numpy.randomimport random

df = pd.DataFrame(random((15,2)),columns=['a','b'])
ax = df.plot(secondary_y=['b'])
plt.show()

Here's what it'll look like

Post a Comment for "Secondary_y=true Changes X Axis In Pandas"