python 散点图图例_带有Colorbar和图例问题的Python散点图

I'm working with a pretty simple example. I create three scatter plots on the same set of axes, and each data set I plot has a different associated colormap. However, the legend does not look as I'd want it to; why is this?

import numpy as np

import matplotlib.pyplot as plt

t = np.linspace(0,10,100)

x = np.random.rand(100,3)

y = np.random.rand(100,3)

colmaps = ['Blues', 'Greys', 'Reds']

for i in range(3):

plt.scatter(x[:,i], y[:,i], c=t, cmap=colmaps[i], label=i)

plt.legend()

plt.show()

This produces a figure like below:

I was hoping for the first label to be blue, the second to be grey, and the third to be red, so they're associated with the colormap, but it looks like that's not how it works. Is there a simple way to do this?

Thanks

解决方案

You can set the legend colors as such:

import numpy as np

import matplotlib.pyplot as plt

t = np.linspace(0,10,100)

x = np.random.rand(100,3)

y = np.random.rand(100,3)

colmaps = ['Blues', 'Greys', 'Reds']

for i in range(3):

plt.scatter(x[:,i], y[:,i], c=t, cmap=colmaps[i], label=i)

plt.legend()

ax = plt.gca()

legend = ax.get_legend()

legend.legendHandles[0].set_color(plt.cm.Blues(.8))

legend.legendHandles[1].set_color(plt.cm.Greys(.8))

legend.legendHandles[2].set_color(plt.cm.Reds(.8))

plt.show()

I set the color of each legendHandle to a specific value in the respective colormap.

If you make the scatter dot's size larger you can see the color and associate individual dots with the legend easier. I also set just one dot per scatter plot in the legend, rather than the default 3, and set the legend's alpha to 0.5, and alpha of scatter plot to 0.7.

...

for i in range(3):

plt.scatter(x[:,i], y[:,i], c=t, cmap=colmaps[i], label=i, s=200, alpha=0.7)

plt.legend(markerscale=0.7, scatterpoints=1)

ax = plt.gca()

legend = ax.get_legend()

legend.legendHandles[0].set_color(plt.cm.Blues(.8))

legend.legendHandles[1].set_color(plt.cm.Greys(.8))

legend.legendHandles[2].set_color(plt.cm.Reds(.8))

legend.get_frame().set_alpha(0.5)

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值