我想重新排序 x 轴刻度标签,以便数据也相应更改。
例子
y = [5,8,9,10]
x = ['a', 'b', 'c', 'd']
plt.plot(y, x)
Run Code Online (Sandbox Code Playgroud)
请注意,我不想通过修改数据的顺序来实现此目的
我的尝试
# attempt 1
fig, ax =plt.subplots()
plt.plot(y,x)
ax.set_xticklabels(['b', 'c', 'a', 'd'])
# this just overwrites the labels, not what we intended
# attempt2
fig, ax =plt.subplots()
plt.plot(y,x)
locs, labels = plt.xticks()
plt.xticks((1,2,0,3)); # This is essentially showing the location
# of the labels to dsiplay irrespective of the order of the tuple.
Run Code Online (Sandbox Code Playgroud)
编辑: 根据这里的评论,有一些进一步的说明。
假设(a,5)图 1 中的第一点。如果我更改了x-axis定义,现在将 a 定义在第三个位置,那么它也会反映在图中,这意味着5在y-axis移动时a如图 2 所示。实现此目的的一种方法是对数据重新排序。但是,我想看看是否可以通过改变轴位置来实现它。总而言之,应该根据我们如何定义自定义轴来绘制数据,而不需要对原始数据重新排序。
Edit2: 根据评论中的讨论,不可能仅通过修改轴标签来做到这一点。任何方法都将涉及修改数据。这是我所面临的原始问题的过度简化。最后,在 pandas 数据框中使用基于字典的标签帮助我按特定顺序对轴值进行排序,同时确保它们各自的值相应变化。
在 x 轴类别的两个不同顺序之间切换可能如下所示,
import numpy as np
import matplotlib.pyplot as plt
x = ['a', 'b', 'c', 'd']
y = [5,8,9,10]
order1 = ['a', 'b', 'c', 'd']
order2 = ['b', 'c', 'a', 'd']
fig, ax = plt.subplots()
line, = ax.plot(x, y, marker="o")
def toggle(order):
_, ind1 = np.unique(x, return_index=True)
_, inv2 = np.unique(order, return_inverse=True)
y_new = np.array(y)[ind1][inv2]
line.set_ydata(y_new)
line.axes.set_xticks(range(len(order)))
line.axes.set_xticklabels(order)
fig.canvas.draw_idle()
curr = [0]
orders = [order1, order2]
def onclick(evt):
curr[0] = (curr[0] + 1) % 2
toggle(orders[curr[0]])
fig.canvas.mpl_connect("button_press_event", onclick)
plt.show()
Run Code Online (Sandbox Code Playgroud)
单击绘图上的任意位置可在order1和之间切换order2。