如何在matplotlib中使用日期时间索引增加xticks?

时间:2018-04-12 23:28:00

标签: python pandas datetime matplotlib

我正在尝试使用matplotlib将股票价格与日期时间指数进行对比。

所以我有一个如下图:

Data looks like this.

我需要它看起来像这样:

Data looks like this.

我认为它可能与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'))

1 个答案:

答案 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)

输出:

enter image description here

编辑:

我们将set_major_locatorMonthLocator

一起使用
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)

输出:

enter image description here