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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)