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?
Try setting the grid after plotting the DataFrame. Also, to get the horizontal grid, you need to use ax2. grid(axis='y') .
By default, Matplotlib does not display gridlines on plots. However, you can use the matplotlib. pyplot. grid() function to easily display and customize gridlines on a plot.
grid() Function. The grid() function in pyplot module of matplotlib library is used to configure the grid lines.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With