如何根据一定的规则改变散点图颜色 [英] How to change scatter plot color according to certain rule

查看:71
本文介绍了如何根据一定的规则改变散点图颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做一个散点图,它的颜色取决于第三个变量.如果变量介于 0 和 1 之间,则给出蓝色"、1-2、红色、2-3、紫色、3-4、绿色、4-5 灰色.我该怎么做?

I have to do a scatter plot that has colors depending on a third variable. If the variable is between 0 and 1, give "blue", 1-2, red, 2-3, purple, 3-4, green, 4-5 gray. How can I do that ?

x = [1,2,3,4,5]
y = [3,4,2,3,4]
c = [1,2,4,0.5,5]

推荐答案

如果您想要颜色图的特定边界,您可以将 mpl.colors.BoundaryNormmpl.colors.ListedColormap 一起使用.

If you want specific boundaries for the colormap you can use mpl.colors.BoundaryNorm together with mpl.colors.ListedColormap.

import matplotlib.pyplot as plt
import matplotlib as mpl

x = [1,2,3,4,5]
y = [3,4,2,3,4]
c = [1,2,4,0.5,5]

cmap = mpl.colors.ListedColormap(['blue','red','magenta', 'green', 'gray'])
c_norm = mpl.colors.BoundaryNorm(boundaries=[0,1,2,3,4,5], ncolors=5)
plt.scatter(x, y, c=c, s=200, cmap=cmap, norm=c_norm)
plt.colorbar()
plt.show()

这给出了这个情节:

这篇关于如何根据一定的规则改变散点图颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆