Control gridline spacing in seaborn

The OP asked about modifying tick distances in Seaborn.

If you are working in Seaborn and you use a plotting feature that returns an Axes object, then you can work with that just like any other Axes object in matplotlib. For example:

import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
from matplotlib.ticker import MultipleLocator

df = sm.datasets.get_rdataset("Guerry", "HistData").data

ax = sns.scatterplot('Literacy', 'Lottery', data=df)

ax.yaxis.set_major_locator(MultipleLocator(10))
ax.xaxis.set_major_locator(MultipleLocator(10))

plt.show()

Put if you are working with one of the Seaborn processes that involve FacetGrid objects, you will see precious little help on how to modify the tick marks without manually setting them. You have dig out the Axes object from the numpy array inside FacetGrid.axes .

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import MultipleLocator

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, )

g.axes[0][0].yaxis.set_major_locator(MultipleLocator(3))

Note the double subscript required. g is a FacetGrid object, which holds a two-dimensional numpy array of dtype=object, whose entries are matplotlib AxesSubplot objects.

If you are working with a FacetGrid that has multiple axes, then each one will have to be extracted and modified.


you can set the tick locations explicitly later, and it will draw the grid at those locations.

The neatest way to do this is to use a MultpleLocator from the matplotlib.ticker module.

For example:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

sns.set_style("whitegrid", {'grid.linestyle': '--'})

fig,ax = plt.subplots()
ax.bar(np.arange(0,50,1),np.random.rand(50)*0.016-0.004,alpha=0.5)

ax.yaxis.set_major_locator(ticker.MultipleLocator(0.005))

plt.show()

enter image description here