Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 523
Aurelie Navir Avatar asked Feb 15 '19 17:02

Aurelie Navir


People also ask

How do I create a horizontal grid in MatPlotLib?

Try setting the grid after plotting the DataFrame. Also, to get the horizontal grid, you need to use ax2. grid(axis='y') .

How do I show gridlines in MatPlotLib?

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.

What does PLT grid () do in Python?

grid() Function. The grid() function in pyplot module of matplotlib library is used to configure the grid lines.


1 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

like image 185
Sheldore Avatar answered Sep 18 '22 14:09

Sheldore