如何在seaborn的facetgrid中设置可读的xticks?

时间:2017-05-01 22:12:34

标签: python pandas matplotlib seaborn

我有一个带有seaborn的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绘制了所有xtick标签,而不仅仅是挑选了几个而且它看起来很可怕:

enter image description here

有没有办法对它进行自定义,以便在x轴上绘制每个第n个刻度而不是全部?

2 个答案:

答案 0 :(得分:11)

您必须手动跳过x标签,如下例所示:

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

答案 1 :(得分:2)

seaborn.pointplot不是此图的正确工具。但答案很简单:使用基本的matplotlib.pyplot.plot函数:

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