我正在以编程方式创建这样的散点图:
(Ipython sample code)
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
d1 = [range(1,11)]
d2 = [range(1,11)]
dcolor = ['red','red','red','green','green','green','blue','blue','blue', 'blue']
colordict{'red': 'monkey', 'green':'whale', 'blue':'cat'}
ax.scatter(d1,d2,alpha=0.8, c=dcolor,edgecolors='none',s=30)
我想为每个不同的点添加一个图例,以便图例包含给定颜色的点和colordict的名称。如果不将散点图的创建分成多个分散调用,这是否可能?由于这发生在自动库中,我宁愿避免对scatter()进行不同的调用。
答案 0 :(得分:4)
我可能会做以下事情。
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
g1 = ([1,2,3], [1,2,3])
g2 = ([4,5,6], [4,5,6])
g3 = ([7,8,9,10], [7,8,9,10])
data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("monkey", "whale", "cat")
for data, color, group in zip(data, colors, groups):
x, y = data
ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)
plt.legend(loc=2)
答案 1 :(得分:1)
我喜欢保持数据及其符号(颜色,标签)比cel更紧密。我发现代码更具可读性,而且更多可检查,而且我常常将它们从某些数据源中解放出来:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
zoo=[]
zoo.append(([4,5,6], [4,5,6], "blue","ape"))
zoo.append(([1,2,3], [1,2,3], "red","monkey"))
for x,y,c,l in zoo:
plt.scatter(x,y,c=c,label=l)
plt.legend(loc="upper left")
答案 2 :(得分:0)
最后,我使用了以下代码:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
d1 = [range(1,11)]
d2 = [range(1,11)]
dcolor = ['red','red','red','green','green','green','blue','blue','blue', 'blue']
ax.scatter(d1,d2,alpha=0.8, c=dcolor,edgecolors='none',s=30)
import matplotlib.patches as mpatches
patch = mpatches.Patch(color='red', label='a')
patch2 = mpatches.Patch(color='red', label='a')
fig.legend( [patch, patch2],['abc', 'xyz'], loc = 'lower center', ncol=5, labelspacing=0. )
这里还没有循环,但这很容易实现。