试图在同一张图中绘制收益和股票价格
Trying to plot Earnings and Stock price in the same graph
我正在尝试在图表上绘制股票价格和收益,但出于某种原因我得到了这个:
Graph1
请看下面我的代码:
import matplotlib.pyplot as plt
import yfinance as yf
import pandas
import pandas_datareader
import matplotlib
t = yf.Ticker("T")
df1 = t.earnings
df1['Earnings'].plot(label = 'earnings', figsize = (15,7), color='green')
print(df1)
df2 = t.history(start = '2018-01-01', end = '2021-01-01', actions = False, rounding = True)
df2['Close'].plot(label = 'price', figsize = (15,7),color = 'blue')
plt.show()
有人可以帮我吗?
提前致谢。
在 pandas 中绘图很容易创建图表,但如果您尝试将它们与时间序列数据叠加,如本例所示,您会遇到问题。有很多方法,但我发现最简单的方法是将数据级别转换为由 matplotlib 管理的 gregorian 日历并创建图形。最后,您可以将其转换为您喜欢的格式等,或使用自动格式化程序和定位器。
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import yfinance as yf
import pandas as pd
t = yf.Ticker("T")
df1 = t.earnings
df1.index = pd.to_datetime(df1.index, format='%Y')
df1.index = mdates.date2num(df1.index)
ax = df1['Earnings'].plot(label='earnings', figsize=(15, 7), color='green')
df2 = t.history(start='2018-01-01', end='2021-01-01', actions=False, rounding=True)
df2.index = mdates.date2num(df2.index)
df2['Close'].plot(label='price', ax=ax,color='blue', secondary_y=True)
#ax.set_xticklabels([x.strftime('%Y-%m') for x in mdates.num2date(df2.index)][::125])
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
plt.show()
我正在尝试在图表上绘制股票价格和收益,但出于某种原因我得到了这个:
Graph1
请看下面我的代码:
import matplotlib.pyplot as plt
import yfinance as yf
import pandas
import pandas_datareader
import matplotlib
t = yf.Ticker("T")
df1 = t.earnings
df1['Earnings'].plot(label = 'earnings', figsize = (15,7), color='green')
print(df1)
df2 = t.history(start = '2018-01-01', end = '2021-01-01', actions = False, rounding = True)
df2['Close'].plot(label = 'price', figsize = (15,7),color = 'blue')
plt.show()
有人可以帮我吗?
提前致谢。
在 pandas 中绘图很容易创建图表,但如果您尝试将它们与时间序列数据叠加,如本例所示,您会遇到问题。有很多方法,但我发现最简单的方法是将数据级别转换为由 matplotlib 管理的 gregorian 日历并创建图形。最后,您可以将其转换为您喜欢的格式等,或使用自动格式化程序和定位器。
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import yfinance as yf
import pandas as pd
t = yf.Ticker("T")
df1 = t.earnings
df1.index = pd.to_datetime(df1.index, format='%Y')
df1.index = mdates.date2num(df1.index)
ax = df1['Earnings'].plot(label='earnings', figsize=(15, 7), color='green')
df2 = t.history(start='2018-01-01', end='2021-01-01', actions=False, rounding=True)
df2.index = mdates.date2num(df2.index)
df2['Close'].plot(label='price', ax=ax,color='blue', secondary_y=True)
#ax.set_xticklabels([x.strftime('%Y-%m') for x in mdates.num2date(df2.index)][::125])
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
plt.show()