matplotlib散点图颜色与第三个变量的函数 [英] matplotlib scatter plot colour as function of third variable

查看:314
本文介绍了matplotlib散点图颜色与第三个变量的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何通过第三个变量使matplotlib的散点函数色点.

I would like to know how to make matplotlib's scatter function colour points by a third variable.

问题 matplotlib中的gnuplot linecolor变量?

Questions gnuplot linecolor variable in matplotlib? and Matplotlib scatterplot; colour as a function of a third variable posed similar queries, however, the answers to those questions don't address my issue: the use of c=arraywhichspecifiespointcolour in the scatter function only sets the fill colour, not the edge colour. This means that the use of c=arr... fails when using markersymbol='+', for instance (because that marker has no fill, only edges). I want points to be coloured by a third variable reliably, regardless of which symbol is used.

有没有一种方法可以通过Matplotlib的散点函数来实现?

Is there a way to achieve this with Matplotlib's scatter function?

推荐答案

这适用于我,使用matplotlib 1.1:

This works for me, using matplotlib 1.1:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.sin(x)

plt.scatter(x, y, marker='+', s=150, linewidths=4, c=y, cmap=plt.cm.coolwarm)
plt.show()

结果:

或者,对于n个点,制作形状为(n,3)的RGB颜色值数组,并将其分配给scatter()edgecolors关键字参数:

Alternatively, for n points, make an array of RGB color values with shape (n, 3), and assign it to the edgecolors keyword argument of scatter():

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 100)
y = np.sin(x)
z = x + 20 * y

scaled_z = (z - z.min()) / z.ptp()
colors = plt.cm.coolwarm(scaled_z)

plt.scatter(x, y, marker='+', edgecolors=colors, s=150, linewidths=4)
plt.show()

结果:

该示例通过将z值缩放到[0,1]范围并使用缩放后的值调用颜色映射plt.cm.coolwarm来获取RGBA值.当以这种方式调用时,matplotlib颜色图将返回RGBA值的数组,每一行都给出相应输入值的颜色.例如:

That example gets the RGBA values by scaling the z values to the range [0,1], and calling the colormap plt.cm.coolwarm with the scaled values. When called this way, a matplotlib colormap returns an array of RGBA values, with each row giving the color of the corresponding input value. For example:

>>> t = np.linspace(0, 1, 5)
>>> t
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ])
>>> plt.cm.coolwarm(t) 
array([[ 0.2298,  0.2987,  0.7537,  1.    ],
       [ 0.5543,  0.6901,  0.9955,  1.    ],
       [ 0.8674,  0.8644,  0.8626,  1.    ],
       [ 0.9567,  0.598 ,  0.4773,  1.    ],
       [ 0.7057,  0.0156,  0.1502,  1.    ]])

这篇关于matplotlib散点图颜色与第三个变量的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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