参数“c"和“cmap"在 matplotlib 散点图中的表现如何? [英] How does parameters 'c' and 'cmap' behave in a matplotlib scatter plot?

查看:50
本文介绍了参数“c"和“cmap"在 matplotlib 散点图中的表现如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 pyplot.scatter(x,y,s,c....) 函数,

matplotlib 文档指出:

<块引用>

c : 颜色、序列或颜色序列,可选,默认:'b'标记颜色.可能的值:

单色格式字符串.一系列颜色规格长度 n.使用 cmap 将 n 个数字映射到颜色的序列和规范.一个二维数组,其中的行是 RGB 或 RGBA.注意 c不应是单个数字 RGB 或 RGBA 序列,因为那是与要进行颜色映射的值数组无法区分.如果你要为所有点指定相同的 RGB 或 RGBA 值,请使用 2-D单行数组.

但是,我不明白如何按照自己的意愿更改数据点的颜色.

我有这段代码:

将 matplotlib.pyplot 导入为 plt将 numpy 导入为 np导入sklearn导入 sklearn.datasets导入 sklearn.linear_model导入 matplotlib%matplotlib 内联matplotlib.rcParams['figure.figsize'] = (13.0, 9.0)# 生成数据集并绘制它np.random.seed(0)X, y = sklearn.datasets.make_moons(200, 噪音=0.55)打印(y)plt.scatter(X[:,0], X[:,1], c=y)#, cmap=plt.cm.Spectral)

这里黑色位于颜色图的开头,绿色位于中间某处,例如 0.5.因此,需要将 vmin 设置为 0,并将 vmax 设置为 vmax*0.5 = 1(使用 1> 要映射到绿色的值),即 vmax = 1./0.5 == 2.

将 matplotlib.pyplot 导入为 plt将 numpy 导入为 npx,y = np.random.rand(2,6)z = np.array([0,0,1,1,0,1])plt.scatter(x,y, c = z,norm = plt.Normalize(vmin=0, vmax=2),cmap = "nipy_spectral")plt.show()

由于可能并不总是存在具有所需颜色的颜色图,并且由于从现有颜色图中获取颜色位置可能并不直接,因此另一种方法是专门为所需目的创建新的颜色图.

这里我们可以简单地创建一个黑色和绿色两种颜色的颜色图.

matplotlib.colors.ListedColormap(["black", "green"])

这里我们不需要任何归一化,因为我们只有两个值,因此可以依赖自动归一化.

将 matplotlib.pyplot 导入为 plt将 matplotlib.colors 导入为 mcolors将 numpy 导入为 npx,y = np.random.rand(2,6)z = np.array([0,0,1,1,0,1])plt.scatter(x,y, c = z, cmap = mcolors.ListedColormap(["black", "green"]))plt.show()

For the pyplot.scatter(x,y,s,c....) function ,

The matplotlib docs states that :

c : color, sequence, or sequence of color, optional, default: 'b' The marker color. Possible values:

A single color format string. A sequence of color specifications of length n. A sequence of n numbers to be mapped to colors using cmap and norm. A 2-D array in which the rows are RGB or RGBA. 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. If you want to specify the same RGB or RGBA value for all points, use a 2-D array with a single row.

However i do not understand how i can change the colors of the datapoints as i wish .

I have this piece of code :

import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import matplotlib


%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (13.0, 9.0)

# Generate a dataset and plot it
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.55)
print(y)
plt.scatter(X[:,0], X[:,1], c=y)#, cmap=plt.cm.Spectral)

the output plot

How can i change the colours to suppose black and green datapoints if i wish ? or something else ? Also please explain what exactly cmap does .

Why my plots are magenta and blue every time i use plt.cm.Spectral ?

解决方案

There are essentially two option on how to colorize scatter points.

1. External mapping

You may externally map values to color and supply a list/array of those colors to the scatter's c argument.

z = np.array([1,0,1,0,1])
colors = np.array(["black", "green"])
plt.scatter(x,y, c=colors[z])

2. Internal mapping

Apart from explicit colors, one can also supply a list/array of values which should be mapped to colors according to a normalization and a colormap.

  • A colormap is a callable that takes float values between 0. and 1. as input and returns a RGB color.
  • A normalization is a callable that takes any number as input and outputs another number, based on some previously set limits. The usual case of Normalize would provide a linear mapping of values between vmin and vmax to the range between 0. and 1..

The natural way to obtain a color from some data is hence to chain the two,

cmap = plt.cm.Spectral
norm = plt.Normalize(vmin=4, vmax=5)
z = np.array([4,4,5,4,5])
plt.scatter(x,y, c = cmap(norm(z)))

Here the value of 4 would be mapped to 0 by the normalzation, and the value of 5 be mapped to 1, such that the colormap provides the two outmost colors.

This process happens internally in scatter if an array of numeric values is provided to c.

A scatter creates a PathCollection, which subclasses ScalarMappable. A ScalarMappable consists of a colormap, a normalization and an array of values. Hence the above is internalized via

plt.scatter(x,y, c=z, norm=norm, cmap=cmap)

If the minimum and maximum data are to be used as limits for the normalization, you may leave that argument out.

plt.scatter(x,y, c=z, cmap=cmap)

This is the reason that the output in the question will always be purple and yellow dots, independent of the values provided to c.

Coming back to the requirement of mapping an array of 0 and 1 to black and green color you may now look at the colormaps provided by matplotlib and look for a colormap which comprises black and green. E.g. the nipy_spectral colormap

Here black is at the start of the colormap and green somewhere in the middle, say at 0.5. One would hence need to set vmin to 0, and vmax, such that vmax*0.5 = 1 (with 1 the value to be mapped to green), i.e. vmax = 1./0.5 == 2.

import matplotlib.pyplot as plt
import numpy as np
x,y = np.random.rand(2,6)
z = np.array([0,0,1,1,0,1])

plt.scatter(x,y, c = z, 
            norm = plt.Normalize(vmin=0, vmax=2),
            cmap = "nipy_spectral")

plt.show()

Since there may not always be a colormap with the desired colors available and since it may not be straight forward to obtain the color positions from existing colormaps, an alternative is to create a new colormaps specifically for the desired purpose.

Here we might simply create a colormap of two colors black and green.

matplotlib.colors.ListedColormap(["black", "green"])

We would not need any normalization here, because we only have two values and can hence rely on automatic normalization.

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
x,y = np.random.rand(2,6)
z = np.array([0,0,1,1,0,1])

plt.scatter(x,y, c = z, cmap = mcolors.ListedColormap(["black", "green"]))

plt.show()

这篇关于参数“c"和“cmap"在 matplotlib 散点图中的表现如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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