Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set readable xticks in seaborn's facetgrid?

i have this plot of a dataframe with seaborn's facetgrid:

import seaborn as sns
import matplotlib.pylab as plt
import pandas
import numpy as np

plt.figure()
df = pandas.DataFrame({"a": map(str, np.arange(1001, 1001 + 30)),
                       "l": ["A"] * 15 + ["B"] * 15,
                       "v": np.random.rand(30)})
g = sns.FacetGrid(row="l", data=df)
g.map(sns.pointplot, "a", "v")
plt.show()

seaborn plots all the xtick labels instead of just picking a few and it looks horrible:

enter image description here

Is there a way to customize it so that it plots every n-th tick on x-axis instead of all of them?

like image 637
jll Avatar asked May 01 '17 22:05

jll


People also ask

What does SNS FacetGrid do?

FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid. The variables should be categorical and the data at each level of the variable will be used for a facet along that axis.

Which plots can be plotted using faceted grids?

The plots it produces are often called “lattice”, “trellis”, or “small-multiple” graphics. It can also represent levels of a third variable with the hue parameter, which plots different subsets of data in different colors.


2 Answers

You have to skip x labels manually like in this example:

import seaborn as sns
import matplotlib.pylab as plt
import pandas
import numpy as np

df = pandas.DataFrame({"a": range(1001, 1031),
                       "l": ["A",] * 15 + ["B",] * 15,
                       "v": np.random.rand(30)})
g = sns.FacetGrid(row="l", data=df)
g.map(sns.pointplot, "a", "v")

# iterate over axes of FacetGrid
for ax in g.axes.flat:
    labels = ax.get_xticklabels() # get x labels
    for i,l in enumerate(labels):
        if(i%2 == 0): labels[i] = '' # skip even labels
    ax.set_xticklabels(labels, rotation=30) # set new labels
plt.show()

enter image description here

like image 122
Serenity Avatar answered Oct 05 '22 09:10

Serenity


The seaborn.pointplot is not the right tool for this plot. But the answer is very simple: use the basic matplotlib.pyplot.plot function:

import seaborn as sns
import matplotlib.pylab as plt
import pandas
import numpy as np

df = pandas.DataFrame({"a": np.arange(1001, 1001 + 30),
                       "l": ["A"] * 15 + ["B"] * 15,
                       "v": np.random.rand(30)})
g = sns.FacetGrid(row="l", data=df)
g.map(plt.plot, "a", "v", marker="o")
g.set(xticks=df.a[2::8])

enter image description here

like image 20
mwaskom Avatar answered Oct 05 '22 08:10

mwaskom