如何仅绘制水平网格线(使用pandas plot + pyplot)

48
我想使用pandas plot仅获取水平网格。
Pandas的集成参数只有“grid=True”或“grid=False”,因此我尝试使用matplotlib pyplot,更改轴参数,具体来说是使用以下代码:
import pandas as pd
import matplotlib.pyplot as plt
fig = plt.figure()
ax2 = plt.subplot()
ax2.grid(axis='x')
df.plot(kind='bar',ax=ax2, fontsize=10, sort_columns=True)
plt.show(fig)

但是我没有得到任何网格线,既没有水平的也没有垂直的。是 Pandas 覆盖了坐标轴吗?还是我做错了什么?

2个回答

89

绘制DataFrame后再设置网格线,要获取水平网格线,请使用 ax2.grid(axis='y')。以下是使用示例数据框的答案。

我已重新构建了如何定义ax2,并利用了subplots

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})

fig, ax2 = plt.subplots()

df.plot(kind='bar',ax=ax2, fontsize=10, sort_columns=True)
ax2.grid(axis='y')
plt.show()

或者,您还可以执行以下操作:直接使用从DataFrame plot返回的轴对象打开水平网格

fig = plt.figure()

ax2 = df.plot(kind='bar', fontsize=10, sort_columns=True)
ax2.grid(axis='y')

第三个选项,正如评论中@ayorgo所建议的那样,是将两个命令链接在一起:

df.plot(kind='bar',ax=ax2, fontsize=10, sort_columns=True).grid(axis='y')

enter image description here


4
将y轴网格线移至后方,在调用grid时的参数中加入zorder=0 - Gene Burinsky
3
zorder=0 这个参数对我没有起作用。 - Craigoh1
尝试使用zorder=-1或更小的值。 - Charly Empereur-mot
1
这个对我很有用,当zorder不起作用时:ax.set_axisbelow(True) - undefined

1
一个替代方案:Matplotlib的plot(和bar)默认不绘制垂直网格线。
plt.bar(df['lab'], df['val'], width=0.4)

或者使用面向对象的方法:

fig, ax = plt.subplots()
ax.bar(df['lab'], df['val'], width=0.5)   # plot bars
ax.tick_params(labelsize=10)              # set ticklabel size to 10
xmin, xmax = ax.get_xlim()
# pad bars on both sides a bit and draw the grid behind the bars
ax.set(xlim=(xmin-0.25, xmax+0.25), axisbelow=True);

res


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