python - 如何更改 seaborn 图中的轴刻度数

标签 python axes seaborn

我希望能够在 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 : falling back to Agg renderer")

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

最佳答案

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

enter image description here

  • 现在应该使用 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))

enter image description here

  • 这也适用于轴级图
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))

enter image description here

关于python - 如何更改 seaborn 图中的轴刻度数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32894854/

相关文章:

python - 基于一系列 pandas 过滤行

python - Pathlib 'normalizes' 带有 "$"的 UNC 路径

python - 从文本中提取艺术家和音乐(正则表达式)

matlab - 在 MATLAB 中绘制箱形图时在 GUI 中重叠轴

python - 如何在seaborn barplot上设置宽度

类似于 R 的 Python 线性回归诊断图

d3.js - d3 不均匀分布缩放

python - 如何删除颜色条

python - 将自定义错误栏添加到seaborn FacetGrid,确认色调和分类x顺序

matplotlib - sns.clustermap 刻度丢失