secondary_y=True changes x axis in pandas

我是研究僧i 提交于 2019-12-18 07:15:14

问题


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()
data[amazon].BULL_MINUS_BEAR.resample("W").plot()
plt.plot()

Yields:

All fine, but I need the green graph to have its own scale. So I use the

amazon_prices.Close.plot()
data[amazon].BULL_MINUS_BEAR.resample("W").plot(secondary_y=True)
plt.plot()

This secondary_y creates a problem, as instead of having the desired graph, I have the following:

Any help with this is hugely appreciated.

(Less relevant notes: I'm (evidently) using Pandas, Matplotlib, and all this is in an Ipython notebook)

EDIT: I've since noticed that removing the resample("W") solves the issue. It is still a problem however as the non-resampled data is too noisy to be visible. Being able to plot sampled data with a secondary axis would be hugely helpful.


回答1:


import matplotlib.pyplot as plt
import pandas as pd
from numpy.random import 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()




回答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.pyplot as plt
import pandas as pd
from numpy.random import 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



来源:https://stackoverflow.com/questions/29685887/secondary-y-true-changes-x-axis-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!