仅水平网格(在 python 中使用 Pandas plot + pyplot)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54714018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:19:55  来源:igfitidea点击:

horizontal grid only (in python using pandas plot + pyplot)

pythonpandasmatplotlib

提问by Aurelie Navir

I would like to get only horizontal grid using pandas plot.

我想使用Pandas图只获得水平网格。

The integrated parameter of pandas only has grid=Trueor grid=False, so I tried with matplotlib pyplot, changing the axes parameters, specifically with this code:

pandas 的集成参数只有grid=Trueor 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)

But I get no grid, neither horizontal nor vertical. Is Pandas overwriting the axes? Or am I doing something wrong?

但我没有网格,既不是水平的也不是垂直的。Pandas 会覆盖轴吗?还是我做错了什么?

回答by Sheldore

Try setting the grid afterplotting the DataFrame. Also, to get the horizontal grid, you need to use ax2.grid(axis='y'). Below is an answer using a sample DataFrame.

绘制 DataFrame尝试设置网格。此外,要获得水平网格,您需要使用ax2.grid(axis='y'). 以下是使用示例 DataFrame 的答案。

I have restructured how you define ax2by making use of subplots.

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()

Alternatively, you can also do the following: Use the axis object returned from the DataFrame plot directly to turn on the horizontal grid

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

fig = plt.figure()

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

Third optionas suggested by @ayorgo in the comments is to chain the two commands as

@ayorgo 在评论中建议的第三个选项是将两个命令链接为

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

enter image description here

在此处输入图片说明