Python 使用子图时更改 x 轴刻度标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19792041/
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 14:38:51  来源:igfitidea点击:

Changing x-axis tick labels when working with subplots

pythonmatplotlibsubplot

提问by HHains

I am plotting multiple boxplots on a single figure using matplotlib following the example here:
http://matplotlib.org/examples/pylab_examples/subplots_demo.html

我正在使用 matplotlib 在单个图形上绘制多个箱线图,以下示例如下:http:
//matplotlib.org/examples/pylab_examples/subplots_demo.html

Everything is working as expected, but I can't figure out how to change the tick labels on the x-axis. I have four data series, which are plotting, but the x-axis ticks are labelled '1, 2, 3, 4' where I would like to assign text to these values.

一切都按预期工作,但我不知道如何更改 x 轴上的刻度标签。我有四个数据系列,它们正在绘图,但 x 轴刻度标记为“1、2、3、4”,我想在其中为这些值分配文本。

My code for the plotting looks like this:

我的绘图代码如下所示:

f, axarr = plt.subplots(2, sharex=True)
axarr[0].boxplot(WS_Bias, whis = 100)
#axarr[0].xticks(range(1, len(Labels)+1),Labels)
axarr[0].axhspan(-0.5, 0.5, facecolor='c', alpha = 0.2)

axarr[1].boxplot(WS_RMS, whis = 100)
#axarr[1].xticks(range(1, len(Labels)+1),Labels)
axarr[1].axhspan(0, 2, facecolor='c', alpha = 0.2)

pl.show()

The commented out lines worked to change the labels when I was dealing with only one dataset but this command is not recognized with the methods I'm using. Pyplot is imported as plt.

当我只处理一个数据集时,注释掉的行用于更改标签,但是我使用的方法无法识别此命令。Pyplot 作为 plt 导入。

采纳答案by Francesco Montesano

Let's assume that axarr[0]has 4 visible x tick labels([1,2,3,4]) and that you want to have instead ['a', 'b', 'c', 'd']

假设axarr[0]有 4 个可见x tick labels( [1,2,3,4]) 并且您想要改为 ['a', 'b', 'c', 'd']

You can set x tick labels with the Axesmethod set_xticklabelsjust doing this:

您可以使用以下Axes方法设置 x 刻度标签set_xticklabels

axarr[0].set_xticklabels(['a', 'b', 'c', 'd'])

Regarding

关于

The commented out lines worked to change the labels when I was dealing with only one dataset but this command is not recognized with the methods I'm using

当我只处理一个数据集时,注释掉的行用于更改标签,但我使用的方法无法识别此命令

xticksis not an Axesmethod but a function in matplotlib.pyplot, that (I think) wraps set/get_xticksand set/get_xtickslabels. So if you try to use it as in your code, you should get an error.

xticks不是Axes方法,而是 中的函数matplotlib.pyplot,(我认为)包装set/get_xticksset/get_xtickslabels。所以如果你尝试在你的代码中使用它,你应该得到一个错误。