gpt4 book ai didi

python - Matplotlib:使用颜色图时线图图例上的颜色错误

转载 作者:行者123 更新时间:2023-12-01 06:41:12 26 4
gpt4 key购买 nike

我正在尝试绘制多条线,每条线都具有从颜色图中选择的唯一颜色。这些线用正确的颜色绘制,但在图例中,每条线都用相同的颜色标记。这是一些示例代码:

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
#values associated with each line
values=(-4,-3,-2,-1, 0,1,2,3,4)
#get an array of colors associated with the list of values
col=plt.cm.viridis(0.125*np.array(values)+0.5)
j=0
x=np.linspace(-5,5,101)
for val in values:
y=get_associated_data(val)
ax.plot(x,y,color=col[j],label='val='+str(val))
j+=1
handles,labels = ax.get_legend_handles_labels()
ax.legend(np.unique(labels))
plt.show()

上面的代码产生这样的图

plot

我该如何解决这个问题?另请注意,标签乱序,我也想修复。
编辑:这是我用来制作绘图的确切代码,包括 @William Miller 对无序图例的修复。

from matplotlib import pyplot as plt
import numpy as np

rc('font', size=16)
rc('text', usetex=True)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel(r'$N^\prime$')
ax.set_ylabel(r'$\Gamma$')
ax.set_title(r'Particle flux at $U=U^{\prime\prime}=0,\varepsilon=20$')
gradlist=(-4,-3,-2,-1, 0,1,2,3,4)
col=plt.cm.viridis(0.125*np.array(gradlist)+0.5)
x=[i/10. for i in range(-50,51)]
j=0
for grad in gradlist:
average_flux=np.load('flux_'+str(grad)+'.npy')
ax.plot(x,average_flux,color=col[j],label=r'$U^\prime=$'+str(grad))
time.sleep(1)
print(grad)
j+=1
handles,labels = ax.get_legend_handles_labels()
labels = np.array(labels)
ax.legend(labels[np.sort(np.unique(labels, return_index=True)[1])])
plt.show()

您将需要以下数据集:https://www.dropbox.com/sh/2l2pot21f5sp6cw/AAD1xJcl-FLVf79ylpf7SZiTa?dl=0

最佳答案

可以按照this answer解决排序问题通过使用 np.uniquenp.sort 的组合来保留顺序。

handles, labels = ax.get_legend_handles_labels()
labels = np.array(labels)
ax.legend(labels[np.sort(np.unique(labels, return_index=True)[1])])
plt.show()

这会给你

enter image description here

着色问题是由于仅使用了 ~900 的前 9 个句柄,而不是与正确的 9 个标签对应的句柄引起的,您可以通过以下方式解决此问题从句柄标签中选择正确的索引,如下所示

handles, labels = ax.get_legend_handles_labels()
idx = np.sort(np.unique(np.array(labels), return_index=True)[1])
ax.legend(np.array(handles)[idx], np.array(labels)[idx])
plt.show()

应该给你正确的结果,

enter image description here

关于python - Matplotlib:使用颜色图时线图图例上的颜色错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59450016/

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