Pandas:如何在pd.DataFrame.plot()中显示x轴上的次要网格线?

27

在使用pandas.DataFrame.plot()绘制DataFrame时,是否有一种控制网格格式的方法?

具体来说,我希望在绘制具有DateTimeIndex x轴的DataFrame时显示次要网格线。

这可以通过DataFrame.plot()实现吗?

df = pd.DataFrame.from_csv(csv_file, parse_dates=True, sep=' ')
3个回答

54

也许这个功能去年还不存在,但在0.19.2版本中,你可以做到:

df.plot(grid=True)

看看文档


27

这将以每周频率绘制S&p500的小刻度和网格线:

import pandas.io.data as web
ts = web.DataReader("^GSPC", "yahoo", start=dt.date( 2013, 6, 1 ))[ 'Adj Close' ]

ax = ts.plot()
xtick = pd.date_range( start=ts.index.min( ), end=ts.index.max( ), freq='W' )
ax.set_xticks( xtick, minor=True )
ax.grid('on', which='minor', axis='x' )
ax.grid('off', which='major', axis='x' )

输入图像描述


不错,但是我怎么使用DataFrame来完成这个问题呢?我找不到ts.index.min()在DataFrame中的等价方法 - df.idxmin()返回一个系列... - user2846226
@user2846226 对于一个 DataFrame,df.index.min() 应该也可以工作,除非它是多重索引。 - behzad.nouri

6

DataFrame.plot() 应该返回一个由 matplotlib 提供的 Axes 对象。

因此,使用 ax = df.plot(...),您可以进行以下操作:

ax.xaxis.grid(True, which='minor', linestyle='-', linewidth=0.25, ...)


1
太棒了,我没有意识到plot()返回一个轴对象。所以我猜在scilab模式下IPython笔记本中显示png图形是因为笔记本检测到了轴对象的存在? - user2846226

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接