Python matplotlib 散点图颜色作为第三个变量的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12965075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matplotlib scatter plot colour as function of third variable
提问by user1082930
I would like to know how to make matplotlib's scatter function colour points by a third variable.
我想知道如何通过第三个变量使 matplotlib 的 scatter 函数颜色点。
Questions
gnuplot linecolor variable in matplotlib?and Matplotlib scatterplot; colour as a function of a third variableposed similar queries, however, the answers to those questions don't address my issue: the use of c=arraywhichspecifiespointcolourin 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 中的 gnuplot linecolor 变量?和Matplotlib 散点图;color 作为第三个变量的函数提出了类似的查询,但是,这些问题的答案并没有解决我的问题:c=arraywhichspecifiespointcolour在 scatter 函数中使用 只设置填充颜色,而不是边缘颜色。这意味着在使用c=arr...时使用失败markersymbol='+',例如(因为该标记没有填充,只有边缘)。我希望点由第三个变量可靠地着色,无论使用哪个符号。
Is there a way to achieve this with Matplotlib's scatter function?
有没有办法用 Matplotlib 的 scatter 函数来实现这一点?
回答by Warren Weckesser
This works for me, using matplotlib 1.1:
这对我有用,使用 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()
Result:
结果:


Alternatively, for n points, make an array of RGB color values with shape (n, 3), and assign it to the edgecolorskeyword argument of scatter():
或者,对于 n 个点,创建一个形状为 (n, 3) 的 RGB 颜色值数组,并将其分配给 的edgecolors关键字参数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()
Result:

结果:

That example gets the RGBA values by scaling the zvalues to the range [0,1], and calling the colormap plt.cm.coolwarmwith 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:
该示例通过将值缩放z到范围 [0,1] 并plt.cm.coolwarm使用缩放值调用颜色图来获取 RGBA值。当以这种方式调用时,matplotlib 颜色图返回一个 RGBA 值数组,每行给出相应输入值的颜色。例如:
>>> 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. ]])

