我想制作一个折线图,其中基本上绘制了(Dog,1),(Cat,2),(Bird,3)等并通过线连接。另外,我希望能够确定标签在X轴上的顺序。 Matplotlib使用“狗”,“猫”和“鸟”标签的顺序自动绘制。尽管我尝试将顺序重新排列为“狗”,“鸟”,“长颈鹿”,“猫”,但该图并没有改变(参见图片)。我应该怎么做才能相应地安排图表?
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)
ax.plot(x,y)
# Set number of ticks for x-axis
ax.set_xticks(range(len(x_ticks_labels)))
# Set ticks labels for x-axis
ax.set_xticklabels(x_ticks_labels)
答案 0 :(得分:1)
您可以预先确定轴上类别的顺序,方法是先按正确的顺序绘制内容,然后再将其删除。
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_labels
内部使用的索引。不幸的是,没有规范的方法可以这样做。在这里我带
this answer中使用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()