如何让matplotlib以与列表相同的顺序订购条形图? [重复]

时间:2022-01-06 21:24:26

This question already has an answer here:

这个问题在这里已有答案:

For a class project I am plotting a barchart. I have a python list with a bunch of labels (even, odd, squares, powers of 3, etc) and a numpy array to hold probabilities associated with each label (in the same order as the labels list). When I plot my chart

对于一个课程项目,我正在绘制条形图。我有一个带有一堆标签的python列表(偶数,奇数,正方形,3的幂等)和一个numpy数组,用于保存与每个标签相关的概率(与标签列表的顺序相同)。当我绘制我的图表时

labels = ["even", "odd", "squares", "powers of 3"]

labels = [“even”,“odd”,“squares”,“powers of 3”]

fig, ax = plt.subplots()
ax.barh(labels, probability)

it puts the barchart values in reverse alphabetical order so instead of it being ordered even, odd, squares it is ordered squares, powers of 3, odd, even, etc. How can I keep my plot in the same order as my list?

它将条形图值按反向字母顺序排列,因此它不是按顺序排序,而是奇数,正方形,它是有序的正方形,3的幂,奇数,偶数等。我如何保持我的情节与我的清单的顺序相同?

1 个解决方案

#1


1  

The first parameter in Axes.barh is the vertical coordinates of the bars, so you'll want something like

Axes.barh中的第一个参数是条形的垂直坐标,所以你需要类似的东西

fig, ax = plt.subplots()
y = np.arange(len(labels))
ax.barh(y, probability)
ax.set_yticks(y)
ax.set_yticklabels(labels)

This way, the bars will be ordered following the order of your list from top to bottom. If you want it the other way around, you could simply do

这样,条形码将按照列表的顺序从上到下排序。如果你想要反过来,你可以这样做

fig, ax = plt.subplots()
y = np.arange(len(labels))
ax.barh(y, probability)
ax.set_yticks(y)
ax.set_yticklabels(labels)
ax.invert_yaxis()

instead.

如何让matplotlib以与列表相同的顺序订购条形图? [重复]

Edit: Given @ImportanceOfBeingErnest's comment, I should note that the above was tested with matplotlib 2.1.1.

编辑:鉴于@ExitanceOfBeingErnest的评论,我应该注意上面的内容是用matplotlib 2.1.1测试的。

#1


1  

The first parameter in Axes.barh is the vertical coordinates of the bars, so you'll want something like

Axes.barh中的第一个参数是条形的垂直坐标,所以你需要类似的东西

fig, ax = plt.subplots()
y = np.arange(len(labels))
ax.barh(y, probability)
ax.set_yticks(y)
ax.set_yticklabels(labels)

This way, the bars will be ordered following the order of your list from top to bottom. If you want it the other way around, you could simply do

这样,条形码将按照列表的顺序从上到下排序。如果你想要反过来,你可以这样做

fig, ax = plt.subplots()
y = np.arange(len(labels))
ax.barh(y, probability)
ax.set_yticks(y)
ax.set_yticklabels(labels)
ax.invert_yaxis()

instead.

如何让matplotlib以与列表相同的顺序订购条形图? [重复]

Edit: Given @ImportanceOfBeingErnest's comment, I should note that the above was tested with matplotlib 2.1.1.

编辑:鉴于@ExitanceOfBeingErnest的评论,我应该注意上面的内容是用matplotlib 2.1.1测试的。