【问题标题】:How to change the number of axis ticks in seaborn plots如何更改 seaborn 图中的轴刻度数
【发布时间】:2015-12-29 22:29:23
【问题描述】:

我希望能够在 Python 3.5 中控制 seaborn 图上的轴刻度数。我非常习惯使用 R 的 ggplot,所以我在 Python 中的类似功能遇到了一些麻烦。

例如,以下是我目前正在使用的数据类型:

test = pd.DataFrame()
test["X"] = [1,2,3,1,2,3]
test["Y"] = [1,5,3,7,2,4]
test["Category"] = ["A", "A", "A", "B", "B", "B"]

我想通过以下方式做类似 ggplot 的 facet_wrap() 的事情:

sns.set(style = "ticks", color_codes = True)
test_plot = sns.FacetGrid(test, col = "Category")
test_plot = (test_plot.map(sns.plt.plot, "X", "Y").add_legend())
test_plot.set_xticks(np.arange(1,4,1))
sns.plt.show(test_plot)

但是,我收到以下错误。问题似乎与在 FacetGrid 中设置轴标签有关,但我不知道如何解决。这是 Python 3 的问题还是在多面图上指定轴的问题?

UserWarning: tight_layout : falling back to Agg renderer

warnings.warn("tight_layout : 回退到 Agg 渲染器")

test_plot.set_xticks(np.arange(1,4,1))
AttributeError: 'FacetGrid' object has no attribute 'set_xticks'

【问题讨论】:

    标签: python axes seaborn


    【解决方案1】:

    set_xticks 是 matplotlib Axes 对象上的方法,但 FacetGrid 有很多轴。您可以遍历它们并在每个上设置 xticks,但更简单的方法是调用 FacetGrid.set(xticks=np.arange(1,4,1)),它将在内部进行循环。

    test_plot = sns.FacetGrid(test, col = "Category")
    test_plot = test_plot.map(sns.lineplot, "X", "Y")
    test_plot.set(xticks=np.arange(1,4,1), yticks=np.arange(1,10,1))
    

    • 现在应该使用sns.relplotkind='line' 来实现
    p = sns.relplot(data=test, kind='line', x='X', y='Y', col='Category')
    p.set(xticks=np.arange(1,4,1), yticks=np.arange(1,10,1))
    

    • 这也适用于轴级图
    p = sns.lineplot(data=test, x='X', y='Y', hue='Category')
    _ = p.set(xticks=np.arange(1,4,1), yticks=np.arange(1,10,1))
    

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 2017-05-11
      • 2020-05-29
      • 2019-08-25
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多