Python 带有由 c 选项指定的颜色标签和图例的 matplotlib 散点图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47006268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matplotlib scatter plot with color label and legend specified by c option
提问by rkjt50r983
I'd like to make this kind of scatter plotwhere the points have colors specified by the "c" option and the legend shows the color's meanings.
我想制作这种散点图,其中点的颜色由“c”选项指定,图例显示颜色的含义。
The data source of mine is like following:
我的数据源如下:
scatter_x = [1,2,3,4,5]
scatter_y = [5,4,3,2,1]
group = [1,3,2,1,3] # each (x,y) belongs to the group 1, 2, or 3.
I tried this:
我试过这个:
plt.scatter(scatter_x, scatter_y, c=group, label=group)
plt.legend()
Unfortunately, I did not get the legend as expected. How to show the legend properly? I expected there are five rows and each row shows the color and group correspondences.
不幸的是,我没有按预期获得传说。如何正确显示图例?我预计有五行,每行显示颜色和组对应关系。
回答by p-robot
As in the example you mentioned, call plt.scatter
for each group:
如您提到的示例,请plt.scatter
为每个组调用:
import numpy as np
from matplotlib import pyplot as plt
scatter_x = np.array([1,2,3,4,5])
scatter_y = np.array([5,4,3,2,1])
group = np.array([1,3,2,1,3])
cdict = {1: 'red', 2: 'blue', 3: 'green'}
fig, ax = plt.subplots()
for g in np.unique(group):
ix = np.where(group == g)
ax.scatter(scatter_x[ix], scatter_y[ix], c = cdict[g], label = g, s = 100)
ax.legend()
plt.show()
回答by HISI
check this out:
看一下这个:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
scatter_x = np.array([1,2,3,4,5])
scatter_y = np.array([5,4,3,2,1])
group = np.array([1,3,2,1,3])
for g in np.unique(group):
i = np.where(group == g)
ax.scatter(scatter_x[i], scatter_y[i], label=g)
ax.legend()
plt.show()