我正在尝试使用matplotlib将股票价格与日期时间指数进行对比。
所以我有一个如下图:
我需要它看起来像这样:
我认为它可能与xticks有关,但我无法弄清楚如何使xticks与日期时间索引一起工作。谢谢你的帮助。
tesla['Open'].plot(title='Open Price', label = 'Tesla', figsize = (16, 6))
ford['Open'].plot(label = 'ford')
gm['Open'].plot(label = 'GM')
plt.legend()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
答案 0 :(得分:0)
像这样:
import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(monthyearFmt)
_ = plt.xticks(rotation=45)
输出:
我们将set_major_locator
与MonthLocator
import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(monthyearFmt)
ax1.xaxis.set_major_locator(mdates.MonthLocator([1,7]))
_ = plt.xticks(rotation=45)
输出: