简体   繁体   English

如何获得两个折线图(使用单独的y轴)以共享相同的日期x轴?

[英]How to get two line charts (using seperate y-axis), to share the same date x-axis?

I have two line charts (GMCR stock price, and the S&P 500) over the same period of time. 我在同一时期有两个折线图(GMCR股票价格和S&P 500)。 Since the S&P 500 closed yesterday at 1,987 and GMCR closed at 54.65, I have the prices on separate y-axis. 自从标准普尔500指数昨天收于1,987点和GMCR收于54.65点以来,我的价格分别位于y轴上。 My question is how do I get the two lines to share the same date x-axis? 我的问题是如何使两条线共享同一日期的x轴?

import pandas as pd
from pandas import DataFrame
from matplotlib import pyplot as plt
import pandas.io.data as web
import datetime as dt

end = dt.datetime.today()
df = web.DataReader('GMCR', 'yahoo', '2007-01-01', end)
sp = web.DataReader('^GSPC', 'yahoo', '2007-01-01', end)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df['Close'],'g-')
ax2.plot(sp['Close'],'b-')

plt.show()

You can add a secondary axis by specifying 'secondary_y=True' when you apply your plot function directly on your dataframe. 将绘图函数直接应用于数据框时,可以通过指定“ secondary_y = True”来添加辅助轴。 Also you can force the graphs to be on the same axes by specifying the axis when calling the plot function (in your code above you have two axes ax1 and ax2 instead of a unique one). 同样,您可以通过在调用绘图功能时指定轴来强制图形位于同一轴上(在上面的代码中,您有两个轴ax1和ax2而不是唯一的一个轴)。

import pandas as pd
from pandas import DataFrame
from matplotlib import pyplot as plt
import pandas.io.data as web
import datetime as dt

end = dt.datetime.today()
df = web.DataReader('GMCR', 'yahoo', '2007-01-01', end)
sp = web.DataReader('^GSPC', 'yahoo', '2007-01-01', end)

fig, ax1 = plt.subplots()
df['Close'].plot(ax=ax1,color='g')
sp['Close'].plot(secondary_y=True, ax=ax1,color='b')

plt.show()

Pass the ax to the secondary plot function and set secondary_y to True . 将斧头传递给次要plot函数,并将secondary_y设置为True

ax = df['Close'].plot(); sp['Close'].plot(ax=ax, secondary_y=True)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM