52

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

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

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?

0

2 Answers 2

100

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

I have restructured how you define ax2 by making use of 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

fig = plt.figure()

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

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

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

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

To move the y-grid lines to the back, add the zorder=0 to the arguments when calling grid
The zorder=0 argument did not work for me
Try zorder=-1 or less
This worked for me when zorder didnt: ax.set_axisbelow(True)
1

An alternative: Matplotlib's plot (and bar) don't draw the vertical grid by default.

plt.bar(df['lab'], df['val'], width=0.4)

or using the object-oriented approach:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.