【问题标题】:how to set readable xticks in seaborn's facetgrid?如何在 seaborn 的 facetgrid 中设置可读的 xticks?
【发布时间】:2017-09-29 08:25:26
【问题描述】:

我有这个带有 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 标签,而不是仅仅挑选几个标签,看起来很糟糕:

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

【问题讨论】:

  • 您可能希望在这里使用plt.plot,因为看起来a 应该是数字。

标签: python pandas matplotlib seaborn


【解决方案1】:

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])

【讨论】:

  • 这是一个简化的解决方案,如果组共享相同的数值则不起作用:df = pd.DataFrame({"a": np.tile(np.arange(1001, 1001 + 15), 2), "l": ["A"] * 15 + ["B"] * 15, "v": np.random.rand(30)})
【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2014-10-02
    • 2016-12-31
    • 1970-01-01
    • 2015-09-19
    • 2020-11-25
    相关资源
    最近更新 更多