Python matplotlib散点图:根据给定条件更改数据点的颜色 [英] Python matplotlib scatter plot : changing colour of data points based on given conditions

查看:8508
本文介绍了Python matplotlib散点图:根据给定条件更改数据点的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据(四个等长数组):

  a = [1,4,5,2 ,8,9,4,6,1,0,6] 
b = [4,7,8,3,0,9,6,2,3,6,7]
c = [9 ,0,7,6,5,6,3,4,1,2,2]
d = [La,Lb,Av,Ac,Av,By,Lh,By,Lg,Ac,Bt]

我正在绘制数组a,b,c的三维图:

  import pylab 
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig .add_subplot(111,projection ='3d')
ax.scatter(a,b,c)

plt.show()
/ pre>

现在,我想使用名为'd'的数组对这些分散点进行着色,如果d中对应的第i个元素值的第一个字母是'L',则将该点的颜色变为红色,如果它以A开头,则为绿色,如果以B p>

所以,第一点(1,4,9)应该是红色,第二(4,7,0)红色,第三(5,8,7)等等。



是否可以这样做?请帮助,如果你有一些想法:)

解决方案

作为 scatter 说明,您可以传递 c 参数:


c:颜色或颜色序列,可选,默认



c可以是单个颜色格式字符串或一系列长度为N的颜色规范
,或使用通过kwargs指定的cmap和norm(见下文)映射到
颜色的N个数字序列。注意
c不应该是单个数字RGB或RGBA序列,因为
与要进行颜色映射的值数组不可区分。 c
可以是一个2-D数组,其中行是RGB或RGBA。


/ p>

  use_colours = {L:red,A:green,B:blue} 
ax.scatter(a,b,c,c = [use_colours [x [0]] for x in d],s = 50)

应产生




I have the following data (four equal-length arrays) :

a = [1, 4, 5, 2, 8, 9, 4, 6, 1, 0, 6]
b = [4, 7, 8, 3, 0, 9, 6, 2, 3, 6, 7]
c = [9, 0, 7, 6, 5, 6, 3, 4, 1, 2, 2]
d = [La, Lb, Av, Ac, Av, By, Lh, By, Lg, Ac, Bt]

I am making a 3d plot of arrays a, b, c :

import pylab
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(a,b,c)

plt.show()

Now, I want to color these scattered points using the array named 'd' such that; if the first letter of corresponding 'i'th element value in d is 'L', then colour the point red, if it starts with 'A' colour it green and if it starts with 'B', colour it blue.

So, first point (1,4,9) should be red, second(4,7,0) red too, third(5,8,7) should be green and so on..

Is it possible to do so? Please help if you have some idea :)

解决方案

As the documentation for scatter explains, you can pass the c argument:

c : color or sequence of color, optional, default

c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however.

So something like

use_colours = {"L": "red", "A": "green", "B": "blue"}
ax.scatter(a,b,c,c=[use_colours[x[0]] for x in d],s=50)

should produce

这篇关于Python matplotlib散点图:根据给定条件更改数据点的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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