带有图像的PyPlot颜色条刻度线问题

时间:2015-05-30 20:59:59

标签: python image matplotlib

我正在尝试使用叠加的拟合曲线绘制图像,但是现在我只提供一个图像示例。

我一直在关注这个例子(http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html),但是当我尝试用图像替换高斯噪声时,颜色条刻度标记不能正确显示(即它们都在左端被粉碎) )。

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from matplotlib import cm
from numpy.random import randn

fig, ax = plt.subplots()

data = np.clip(randn(250, 250), -1, 1)
#data = Image.open('testTop.tif')

cax = ax.imshow(data, interpolation='nearest', cmap=cm.afmhot)
ax.set_title('colorBar fun')

cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])# horizontal colorbar

plt.show()

correct colorbar

#data = np.clip(randn(250, 250), -1, 1)
data = Image.open('testTop.tif')

incorrect colorbar

显示图像是否存在扭曲色条的内在问题,或者是否有其他明显缺少的东西?

1 个答案:

答案 0 :(得分:2)

颜色条轴在随机鼻子的示例中仅从-1到1,因为数据范围从-1到1.您使用的tif图像可能具有不同的值范围。您可以获取正在绘制的数据的最小值和最大值,并使用它来设置颜色条刻度。这是一个适用于随机数据和图像的示例:

import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from matplotlib import cm
from numpy.random import randn

# Load sample image 
image_file = cbook.get_sample_data('grace_hopper.png')
data = plt.imread(image_file)
data = data[:,:,0]  # Take only one channel for a grey scale image. 

#data = np.clip(randn(250, 250), -1, 1)

fig, ax = plt.subplots()

cax = ax.imshow(data, interpolation='nearest', cmap=cm.afmhot)
ax.set_title('colorBar fun')

dataMin = np.amin(data)
dataMax = np.amax(data)
mid = ((dataMax - dataMin) / 2) + dataMin
cbar = fig.colorbar(cax, ticks=[dataMin, mid, dataMax], orientation='horizontal')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])# horizontal colorbar

plt.show()

image with color bar with ticks