Matplotlib:没有字符串和轴反转的分类图

Matplotlib: categorical plot without strings and inversion of axes

让我们来看看 Python 的这个片段:

import matplotlib.pyplot as plt

x = [5,4,3,2,1,0]
x_strings = ['5','4','3','2','1','0']
y = [0,1,2,3,4,5]

plt.figure()

plt.subplot(311)
plt.plot(x, y, marker='o')

plt.subplot(312)
plt.plot(x_strings, y, marker='^', color='red')

plt.subplot(313)
plt.plot(x, y, marker='^', color='red')
plt.gca().invert_xaxis()

plt.show()

产生这三个子图:

在顶部子图中,x 值自动递增排序,尽管它们在给定列表中的顺序。如果我想精确地按照 x 的给定顺序绘制 xy,那么我有两种可能性:

1) 将 x 值转换为字符串并绘制分类图——这是中间的子图。

2) 反转 x 轴——这是底部子图。

问题:有没有其他方法可以做分类图,但不需要将数字转换为字符串,也不需要反转 x 轴?

附加功能:

如果我使用 set_xticklabels(list),那么由于某些不明确的原因,列表中的第一个元素将被跳过(无论我指的是 x 还是 x_strings 列表) , 结果情节也很奇怪:

import matplotlib.pyplot as plt

x = [5,4,3,2,1,0]
x_strings = ['5','4','3','2','1','0']
y = [0,1,2,3,4,5]

fig, ax = plt.subplots()

ax.set_xticklabels(x)
ax.plot(x, y, marker='^', color='red')

plt.show()

两种尝试的解决方案似乎都是可行的。或者,您始终可以通过绘制整数并根据自己的喜好设置刻度标签来模拟分类图。

import matplotlib.pyplot as plt

x = [5,4,3,2,1,0]
y = [0,1,2,3,4,5]

fig, ax = plt.subplots()

ax.plot(range(len(y)), y, marker='^', color='red')

ax.set_xticks(range(len(y)))
ax.set_xticklabels(x)

plt.show()

我找到了另一种方法,既没有分类也没有 x 轴反转!

ax = plt.subplot()
ax.set_xlim(x[0],x[-1], auto=True) # this line plays the trick
plt.plot(x, y, marker='^', color='red')