【问题标题】:Matplotlib set x tick labels does not swap orderMatplotlib 设置 x 刻度标签不交换顺序
【发布时间】:2019-07-02 17:36:59
【问题描述】:

我想制作一个折线图,其中基本上 (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)

【问题讨论】:

  • 您的x 列表中没有“长颈鹿”。你的问题到底是什么?想要的图应该是什么样子的?
  • @Bazingaa 我认为问题的关键在于 Giraffe 不在 x 中(除了所需的自定义排序)。
  • @Bazingaa 为混乱道歉,我的目的是根据我确定的标签顺序而不是 matplotlib 的自动排序来显示图表。
  • @ImportanceOfBeingErnest 回答了这个问题。谢谢!!

标签: matplotlib


【解决方案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()

两种情况的结果

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2019-11-18
    • 2022-01-01
    • 1970-01-01
    • 2013-12-30
    • 2012-03-14
    相关资源
    最近更新 更多