如何在Matplotlib中显示X轴网格线

4

这段代码绘制了Pandas数据框中特定的列,并提供了多个选项:

area_tabs=['12']
nrows = int(math.ceil(len(area_tabs) / 2.))
figlen=nrows*7 #adjust the figure size height to be sized to the number of rows
plt.rcParams['figure.figsize'] = 25,figlen 
fig, axs = plt.subplots(nrows, 2, sharey=False)
for ax, area_tabs in zip(axs.flat, area_tabs):
    actdf, aname = get_data(area_tabs)
    lastq,fcast_yr,projections,yrahead,aname,actdf,merged2,mergederrs,montdist,ols_test,mergedfcst=do_projections(actdf)
mergedfcst.tail(12).plot(ax=ax, title='Area: {0} Forecast for 2014 {1} \
 vs. 2013 actual of {2}'.format(unicode(aname),unicode(merged2['fcast']  [-1:].values),unicode(merged2['Units'][-2:-1].values)))

使用类似下面这样的数据框,其中日期为索引:

           Units    fcast
date        
2014-01-01   384     302
2014-02-01   NaN     343
2014-03-01   NaN     396
2014-04-01   NaN     415
2014-05-01   NaN     483
2014-06-01   NaN     513

我得到的图表看起来像这样: 水平背景网格(单位)显示正常,但我无法弄清楚如何显示垂直的月度网格。我怀疑它可能被视为次要的?但即使是这样,也看不到在pyplot/matplot中指定它的位置。

len(area_tabs) = 1 时,你为什么要制作两个轴? - Paul H
是的,因为这只是测试代码,最终将有一系列选项卡(20+)。 - dartdog
1个回答

5
在你的for循环中添加ax.xaxis.grid(True, which=['major'|'minor'|'both'])应该可以解决问题。
主要的问题在于尽可能避免使用plt状态机函数,而是直接操作轴对象。

编辑:

不要太过字面理解上面的代码片段。竖杠分隔的值只是伪正则表达式中提供的选项。如果您想要主要刻度线,请使用:ax.xaxis.grid(True, which='major')

如果我使用ax.xaxis.grid(True, which=['minor'])或者使用major,(或者如果我完全使用你的代码...在for循环的第一行我会得到一个AttributeError: 'list' object has no attribute 'lower'错误,而且如果我只是使用ax.xaxis.grid(True),没有任何变化。 - dartdog
使用您的代码直接运行,我得到了TypeError: unsupported operand type(s) for |: 'str' and 'str'。 - dartdog
@dartdog,“minor”和“major”等只是选项。不要字面上使用它们。 - Paul H
这是我之前的想法,但是使用每个变量本身时出现了“没有属性”的错误。 - dartdog
@dartdog 这是因为您将它们放在列表中,而函数需要一个标量字符串。 - Paul H
做到了,谢谢 >>> ax.xaxis.grid(True, which='both') - dartdog

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