gpt4 book ai didi

python - 修改绘图轴,使其刻度标签的顺序和它们各自的点相应地改变——而不修改数据本身

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:29 26 4
gpt4 key购买 nike

我想重新排序 x 轴刻度标签,以便数据也相应地更改。

示例

y = [5,8,9,10]
x = ['a', 'b', 'c', 'd']
plt.plot(y, x)

Original plot

通过修改轴刻度的位置,我希望绘图看起来像什么。 Intended image

请注意,我不想通过修改数据的顺序来实现这一点

我的尝试

# 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.

编辑:根据这里的评论,有一些进一步的说明。

假设图 1 中的第一个点 (a,5)。如果我更改了我的 x-axis 定义,现在 a 被定义在第三个位置,然后它也会反射(reflect)在图中,这意味着 y 轴 上的 5a 移动,如图 2 所示。实现此目的的一种方法是重新排序数据。但是,我想看看是否可以通过更改轴位置以某种方式实现它。总而言之,应根据我们定义自定义轴的方式绘制数据,而无需对原始数据进行重新排序。

编辑2:根据评论中的讨论,仅修改轴标签是不可能的。任何方法都涉及修改数据。这是对我面临的原始问题的过度简化。最后,在 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()

单击图上的任意位置可在 order1order2 之间切换。

关于python - 修改绘图轴,使其刻度标签的顺序和它们各自的点相应地改变——而不修改数据本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56400876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com