Matplotlib设置x刻度标签不交换顺序

时间:2019-02-08 13:04:23

标签: matplotlib

我想制作一个折线图,其中基本上绘制了(Dog,1),(Cat,2),(Bird,3)等并通过线连接。另外,我希望能够确定标签在X轴上的顺序。 Matplotlib使用“狗”,“猫”和“鸟”标签的顺序自动绘制。尽管我尝试将顺序重新排列为“狗”,“鸟”,“长颈鹿”,“猫”,但该图并没有改变(参见图片)。我应该怎么做才能相应地安排图表?enter image description here

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)

1 个答案:

答案 0 :(得分:1)

使用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_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()

两种情况下的结果

enter image description here