我该如何用对等色来绘制对数归一化的imshow图,该色带代表matplotlib中的原始数据 [英] How can I draw a log-normalized imshow plot with a colorbar representing the raw data in matplotlib

查看:44
本文介绍了我该如何用对等色来绘制对数归一化的imshow图,该色带代表matplotlib中的原始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib绘制对数归一化的图像,但我希望原始原始图像数据在颜色栏中显示,而不是[0-1]间隔.我感觉通过使用某种标准化对象而不是事先不转换数据,可以采用一种更加matplotlib'y的方式……在任何情况下,原始图像中都可能存在负值.

I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any case, there could be negative values in the raw image.

import matplotlib.pyplot as plt
import numpy as np

def log_transform(im):
    '''returns log(image) scaled to the interval [0,1]'''
    try:
        (min, max) = (im[im > 0].min(), im.max())
        if (max > min) and (max > 0):
            return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
    except:
        pass
    return im

a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)

我尝试过使用 cb.set_array,但这似乎没有任何作用,而 cb.set_clim,却完全重新调整了颜色.

I've tried using cb.set_array, but that didn't appear to do anything, and cb.set_clim, but that rescales the colors completely.

推荐答案

是的!使用 LogNorm.这是我写的一个实用程序的代码摘录,用于以对数刻度显示混乱矩阵.

Yes, there is! Use LogNorm. Here is a code excerpt from a utility that I wrote to display confusion matrices on a log scale.

from pylab import figure, cm
from matplotlib.colors import LogNorm
# C = some matrix
f = figure(figsize=(6.2,5.6))
ax = f.add_axes([0.17, 0.02, 0.72, 0.79])
axcolor = f.add_axes([0.90, 0.02, 0.03, 0.79])
im = ax.matshow(C, cmap=cm.gray_r, norm=LogNorm(vmin=0.01, vmax=1))
t = [0.01, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0]
f.colorbar(im, cax=axcolor, ticks=t, format='$%.2f$')
f.show()

这篇关于我该如何用对等色来绘制对数归一化的imshow图,该色带代表matplotlib中的原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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