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

2024-04-23 23:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有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刻度,而不是所有刻度?


Tags: 数据importmappandasdfmatplotlibasnp
2条回答

您必须手动跳过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

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

相关问题 更多 >