How to draw horizontal grid only (using pandas plot + pyplot)

Question:

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?

Asked By: Aurelie Navir

||

Answers:

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

Answered By: Sheldore

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

Answered By: cottontail
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.