如何将整数映射到 matplotlib 中的颜色? [英] How to map integers to colors in matplotlib?

查看:101
本文介绍了如何将整数映射到 matplotlib 中的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:做了一个糟糕的黑客,我选择了一个颜色图渐变(在我的例子中是'nipy_spectral')并制作了一个字典,将我想要的颜色映射到一个整数,这样绘图函数就会绘制正确的颜色.它涉及很多数字.如果没有更好的解决方法,我将作为解决方案发布.


我从用于混淆矩阵的另一个绘图函数改编了以下绘图函数:

  def plot_matrix(rm,title ='Robot World',cmap = plt.cm.Blues):plt.imshow(rm,插值='最近',cmap = cmap)plt.title(标题)plt.tight_layout()

我有以下形式的矩阵:

<块引用>

[ 1,3,1,0,1,3,4]

[3,1,0,1,2,3,0]

...多几行.

理想情况下,我绘制这个矩阵使得矩阵内的整数值对应于颜色:['black','blue','yellow','green','red']在类似于matplotlib的示例站点上用于最接近插值的示例矩阵中的绘图中:


我认为答案必须是某种自定义cmap,例如:

cmap = { 0:'k',1:'b',2:'y',3:'g',4:'r' }

我将如何在 matplotlib 中执行此操作?我正在查看自定义颜色图网站,似乎比我尝试做的事涉及更多……

解决方案

您可以使用

Update: Did a lousy hack where I choose a colormap gradient ('nipy_spectral' in my case) and make a dictionary that maps the color I want to an integer such that the plotting function will plot the correct color. It involves a lot of futzing around with the numbers. I'll post as solution if nothing better comes along.


I have the following plotting function adapted from another plotting function I used for a confusion matrix:

def plot_matrix(rm, title='Robot World', cmap=plt.cm.Blues):
    plt.imshow(rm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.tight_layout()

And I have a matrix of the following form:

[ 1,3,1,0,1,3,4]

[ 3,1,0,1,2,3,0]

... for a few more rows.

Ideally, I plot this matrix such that the integer values within the matrix correspond to the colors: ['black','blue','yellow','green','red'] in a plot that looks something like the example matrix on matplotlib's example site for interpolation nearest:


I think the answer must be some kind of custom cmap, like:

cmap = { 0:'k',1:'b',2:'y',3:'g',4:'r' }

How would I do this in matplotlib? I am looking at the custom colormap site, and it seems a whole lot more involved than what I am trying to do...

解决方案

You can use a ListedColormap to do a discrete colormap:

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

def plot_matrix(rm, title='Robot World', cmap=plt.cm.Blues):
    plt.imshow(rm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.tight_layout()
    plt.show()

cmap = colors.ListedColormap(['k','b','y','g','r'])
rm = np.random.randint(0,4,(5,5))
plot_matrix(rm,cmap=cmap)

, the result is this:

这篇关于如何将整数映射到 matplotlib 中的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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