Matplotlib集合x记号标签不交换顺序

Matplotlib集合x记号标签不交换顺序,matplotlib,Matplotlib,我想做一个折线图,基本上(狗,1),(猫,2),(鸟,3)等等都是用线绘制和连接的。另外,我希望能够确定标签在X轴上的顺序。Matplotlib使用顺序“狗”、“猫”和“鸟”标签自动打印。尽管我试图将顺序重新排列为“狗”、“鸟”、“长颈鹿”、“猫”,但图形并没有改变(见图)。我应该怎么做才能相应地排列图表 使用matplotlib的分类功能 您可以通过先按正确的顺序打印某个对象,然后再次删除该对象来预先确定轴上类别的顺序 import numpy as np import matplotlib.

我想做一个折线图,基本上(狗,1),(猫,2),(鸟,3)等等都是用线绘制和连接的。另外,我希望能够确定标签在X轴上的顺序。Matplotlib使用顺序“狗”、“猫”和“鸟”标签自动打印。尽管我试图将顺序重新排列为“狗”、“鸟”、“长颈鹿”、“猫”,但图形并没有改变(见图)。我应该怎么做才能相应地排列图表

使用matplotlib的分类功能 您可以通过先按正确的顺序打印某个对象,然后再次删除该对象来预先确定轴上类别的顺序

import numpy as np
import matplotlib.pyplot as plt

x = ['Dog','Cat','Bird','Dog','Cat','Bird','Dog','Cat','Cat','Cat']
y = [1,2,3,4,5,6,7,8,9,10]
x_ticks_labels = ['Dog','Bird','Giraffe','Cat']

fig, ax = plt.subplots(1,1) 

sentinel, = ax.plot(x_ticks_labels, np.linspace(min(y), max(y), len(x_ticks_labels)))
sentinel.remove()
ax.plot(x,y, color="C0", marker="o")

plt.show()
确定价值指数 另一个选项是确定
x
中的值在
x_tick_标签
中的索引。不幸的是,没有一种规范的方法可以做到这一点;这是我的房间 使用
np.where
的解决方案。然后可以简单地根据这些索引绘制
y
值,并相应地设置刻度和刻度标签

import numpy as np
import matplotlib.pyplot as plt

x = ['Dog','Cat','Bird','Dog','Cat','Bird','Dog','Cat','Cat','Cat']
y = [1,2,3,4,5,6,7,8,9,10]
x_ticks_labels = ['Dog','Bird','Giraffe','Cat']

xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]

fig, ax = plt.subplots(1,1) 

ax.plot(ind,y, color="C0", marker="o")
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)

plt.show()
两种情况下的结果

您的
x
列表中没有“长颈鹿”。你的问题到底是什么?想要的身材应该是什么样子?@Bazingaa我想问题的关键是长颈鹿不在
x
(除了所需的定制订单之外)。@Bazingaa对混淆表示歉意,我的目的是根据我确定的标签顺序来显示图表,而不是matplotlib的自动排序。@ImportanceOfBeingErnest回答了这个问题。谢谢你!!
import numpy as np
import matplotlib.pyplot as plt

x = ['Dog','Cat','Bird','Dog','Cat','Bird','Dog','Cat','Cat','Cat']
y = [1,2,3,4,5,6,7,8,9,10]
x_ticks_labels = ['Dog','Bird','Giraffe','Cat']

xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]

fig, ax = plt.subplots(1,1) 

ax.plot(ind,y, color="C0", marker="o")
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)

plt.show()