Python 更改 seaborn 图中 x 轴刻度的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32894854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:26:18  来源:igfitidea点击:

Change number of x-axis ticks in seaborn plots

pythonaxesseaborn

提问by Nancy

I would like to be able to control the number of axis ticks on a seaborn plot in Python 3.5. I'm very accustomed to using R's ggplot, so I'm having some trouble with analogous functionality in Python.

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

As a example, here is the kind of data I'm currently working with:

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

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

And I would like to do something like ggplot's facet_wrap() by doing:

我想通过执行以下操作来执行类似 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)

However, I get the following errors. The problem seems to be something about setting axis labels in FacetGrid, but I don't know how to resolve it. Is this an issue with Python 3 or with specifying axes on a facetted plot?

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

UserWarning: tight_layout : falling back to Agg renderer

warnings.warn("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'

采纳答案by mwaskom

set_xticksis a method on a matplotlib Axes object, but FacetGridhas many axes. You could loop over them and set the xticks on each one, but an easier way is to call FacetGrid.set(xticks=np.arange(1,4,1)), which will do the loop internally.

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