Matplotlib散点图和颜色图的问题 [英] Issue with Matplotlib scatterplot and Color maps

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

问题描述

我正在一个项目中,该项目涉及将颜色图应用于matplotlib中生成的散点图.我的代码可以按预期工作,除非生成的散点图恰好有四个点.下面的代码对此进行了说明:

I am working on a project that involves applying colormaps to scatterplots generated in matplotlib. My code works as expected, unless the scatterplot being generated has exactly four points. This is illustrated in the following code:

import numpy as np
import matplotlib.pyplot as plt

cmap = plt.get_cmap('rainbow_r')

z = np.arange(20)
plt.close()
plt.figure(figsize=[8,6])

for i in range(1,11):
    x = np.arange(i)
    y = np.zeros(i) + i
    plt.scatter(x, y, c=cmap(i / 10), edgecolor='k', label=i, s=200)

plt.legend()
plt.show()

此代码生成以下图:

每行应包含相同颜色的点,但对于具有四个点的行则不是这种情况.

Each row should consist of points of the same color, but that is not the case for the row with four points.

我认为这与从颜色表中选择的颜色以4个浮点数的元组返回的事实有关,如下所示:

I assume it has to do with the fact that the color selected from the colormap is returned as a tuple of 4 floats, as illustrated below:

print(cmap(0.4))
>>  (0.69999999999999996, 0.95105651629515364, 0.58778525229247314, 1.0)

假设这是问题的根源,我不知道如何解决.

Assuming that this is the source of the issue, I have no idea how to fix it.

推荐答案

这是一个常见的陷阱,例如文档特别提及:

This is a common pitfall, such that the documentation espectially mentions it:

请注意,c不应为单个数字RGB或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.

它也直接为您提供解决方案:

It also directly gives you the solution:

c可以是二维数组,其中的行为RGB或RGBA,包括单行为所有点指定相同颜色的情况.

c can be a 2-D array in which the rows are RGB or RGBA, however, including the case of a single row to specify the same color for all points.

在这种情况下:

c=np.atleast_2d(cmap(i/10.))


当然,可以使用其他选项将颜色指定为字符串,以解决这种歧义.


A different option is of course to specify the color as a string such that this abiguity is resolved.

c = matplotlib.colors.rgb2hex(cmap(i/10.))

这篇关于Matplotlib散点图和颜色图的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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