英文:
Trouble with a plot legend
问题
我有两个数组,x和y,用于绘图,还有一个第三个数组z,它标识了x和y的点。数组z中的整数是重复的,所以我创建了一个z2数组来标识唯一的值。我需要制作一个图,从z2数组中显示一个图例,绘制的点反映相同的颜色。但是实际上,我在图中得到的是一种颜色,而在图例中得到了不同的颜色。这是我的代码。
import matplotlib.pyplot as plt
import numpy as np
x = [0.54638897, 0.74436089, 0.36840323, 0.67932601, 0.56410781, 0.20797502,
0.54681392, 0.47598874, 0.33771962, 0.6626352, 0.06115377, 0.37277143,
0.43410935, 0.97386762, 0.69819935, 0.62578862, 0.15594451, 0.43509243,
0.3712351, 0.94039755]
y = [0.45281763, 0.85509999, 0.65361185, 0.87928696, 0.00333544, 0.92478824,
0.95129375, 0.15493552, 0.06571068, 0.31728336, 0.58555545, 0.52413135,
0.43512262, 0.91267715, 0.56997665, 0.93413675, 0.57615435, 0.18518019,
0.98207871, 0.99850326]
z = [1,1,1,1,5,5,5,11,11,11,1,1,6,6,8,8,11,9,9]
z2 = np.unique(z)
print(z2)
for i in (z2):
plt.plot(x, y, 'o', label=i)
plt.plot(x, y, 'o')
plt.legend()
plt.grid()
这是我得到的图。
我需要,例如,x和y值[0到3]对应于z = 1在图中。根据图例,这些点中的每一个都应该是蓝色的。我知道我在这里做错了些什么。任何建议将不胜感激。
英文:
I have two arrays, x and y, for plotting, and a third array, z, that identifies the x and y points. The integers in z are repeated, so I made a z2 array that identifies the unique values. I need to make a plot that shows a legend from the z2 array, with the plotted points reflecting those same colors. But instead I get all one color in the plot and different colors in the legend. Here is my code.
import matplotlib.pyplot as plt
import numpy as np
x = [0.54638897, 0.74436089, 0.36840323, 0.67932601, 0.56410781, 0.20797502,
0.54681392, 0.47598874, 0.33771962, 0.6626352, 0.06115377, 0.37277143,
0.43410935, 0.97386762, 0.69819935, 0.62578862, 0.15594451, 0.43509243,
0.3712351, 0.94039755]
y = [0.45281763, 0.85509999, 0.65361185, 0.87928696, 0.00333544, 0.92478824,
0.95129375, 0.15493552, 0.06571068, 0.31728336, 0.58555545, 0.52413135,
0.43512262, 0.91267715, 0.56997665, 0.93413675, 0.57615435, 0.18518019,
0.98207871, 0.99850326]
z = [1,1,1,1,5,5,5,11,11,11,1,1,6,6,8,8,11,9,9]
z2 = np.unique(z)
print(z2)
for i in (z2):
plt.plot(x, y, 'o', label=i)
plt.plot(x, y, 'o')
plt.legend()
plt.grid()
And this is the plot I get.
I need, for example, x and y values [0 through 3] to correspond to z = 1 in the plot. According to the legend, each of those dots would be colored blue. I know I'm doing something wrong here. Any advice would be appreciated.
答案1
得分: 2
不需要使用 np.unique
。而是使用 plt.scatter
,并使用 c
参数,如下所示:
plt.scatter(x, y, c=z, marker='o')
还要注意,z
具有19个元素,而 x
和 y
每个具有20个元素。
英文:
You don't need to use np.unique
at all. Instead, use plt.scatter
and use the c
argument, like so:
plt.scatter(x, y, c=z, marker='o')
It also appears that z
has 19 elements, while x
and y
have 20 each.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论