Python 用相同的颜色条显示子图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17989917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Imshow subplots with the same colorbar
提问by lovespeed
I want to make 4 imshow
subplots but all of them share the same colormap. Matplotlib automatically adjusts the scale on the colormap depending on the entries of the matrices. For example, if one of my matrices has all entires as 10 and the other one has all entries equal to 5 and I use the Greys
colormap then one of my subplots should be completely black and the other one should be completely grey. But both of them end up becoming completely black. How to make all the subplots share the same scale on the colormap?
我想制作 4imshow
个子图,但它们都共享相同的颜色图。Matplotlib 根据矩阵的条目自动调整颜色图上的比例。例如,如果我的一个矩阵的所有元素为 10,另一个矩阵的所有条目都等于 5 并且我使用Greys
颜色图,那么我的一个子图应该是完全黑色的,另一个应该是完全灰色的。但他们两个最终都变成了全黑。如何使所有子图在颜色图上共享相同的比例?
采纳答案by tiago
To get this right you need to have all the images with the same intensity scale, otherwise the colorbar()
colours are meaningless. To do that, use the vmin
and vmax
arguments of imshow()
, and make sure they are the same for all your images.
要做到这一点,您需要让所有图像具有相同的强度等级,否则colorbar()
颜色毫无意义。为此,请使用 的vmin
和vmax
参数imshow()
,并确保它们对所有图像都相同。
E.g., if the range of values you want to show goes from 0 to 10, you can use the following:
例如,如果要显示的值范围从 0 到 10,则可以使用以下命令:
import pylab as plt
import numpy as np
my_image1 = np.linspace(0, 10, 10000).reshape(100,100)
my_image2 = np.sqrt(my_image1.T) + 3
subplot(1, 2, 1)
plt.imshow(my_image1, vmin=0, vmax=10, cmap='jet', aspect='auto')
plt.subplot(1, 2, 2)
plt.imshow(my_image2, vmin=0, vmax=10, cmap='jet', aspect='auto')
plt.colorbar()
回答by Ramon Crehuet
It may be that you don't know beforehand the ranges of your data, but you may know that somehow they are compatible. In that case, you may prefer to let matplotlib choose those ranges for the first plot and use the same range for the remaining plots. Here is how you can do it. The key is to get the limits with properties()['clim']
可能您事先不知道数据的范围,但您可能知道它们以某种方式兼容。在这种情况下,您可能更愿意让 matplotlib 为第一个图选择这些范围,并为其余图使用相同的范围。这是您如何做到的。关键是要得到限制properties()['clim']
import numpy as np
import matplotlib.pyplot as plt
my_image1 = np.linspace(0, 10, 10000).reshape(100,100)
my_image2 = np.sqrt(my_image1.T) + 3
fig, axes = plt.subplots(nrows=1, ncols=2)
im = axes[0].imshow(my_image1)
clim=im.properties()['clim']
axes[1].imshow(my_image2, clim=clim)
fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.5)
plt.show()