本文介绍了secondary_y=True 更改 pandas 中的 x 轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

产量:

一切都很好,但我需要绿色图表有自己的比例.所以我使用

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()

这个 secondary_y 产生了一个问题,因为我没有获得所需的图表,而是有以下内容:

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

非常感谢您对此的任何帮助.

Any help with this is hugely appreciated.

(不太相关的注释:我(显然)使用 Pandas、Matplotlib,所有这些都在 Ipython 笔记本中)

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

我已经注意到删除 resample("W") 解决了这个问题.然而,这仍然是一个问题,因为未重新采样的数据噪声太大而无法看到.能够绘制带有辅助轴的采样数据将非常有帮助.

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.

推荐答案

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()

这篇关于secondary_y=True 更改 pandas 中的 x 轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 20:32