我不能让imshow图形上的颜色条与图形的高度相同,因为事后使用Photoshop是不够的。我怎样才能使高度匹配?
发布于 2013-08-13 04:15:55
使用matplotlib AxisDivider可以很容易地做到这一点。
链接页面中的示例在不使用子图的情况下也可以使用:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
发布于 2014-11-04 02:18:07
这种组合(以及接近这些值的值)似乎对我来说是“神奇的”,无论显示器的大小如何,都可以保持颜色条按比例缩放到绘图。
plt.colorbar(im,fraction=0.046, pad=0.04)
它也不需要共享轴,这可以使绘图脱离正方形。
发布于 2019-07-05 18:01:10
我很欣赏上面所有的答案。然而,正如一些答案和评论指出的那样,axes_grid1
模块不能处理GeoAxes,而调整fraction
、pad
、shrink
和其他类似参数不一定能给出非常精确的顺序,这真的让我很困扰。我认为,给colorbar
自己的axes
可能是解决上述所有问题的更好的解决方案。
代码
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))
# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
结果
后来,我发现matplotlib.pyplot.colorbar
official documentation还提供了ax
选项,这是为颜色栏提供空间的现有轴。因此,它对于多个子图很有用,请参见下文。
代码
fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)
结果
同样,您也可以通过指定cax来实现类似的效果,从我的角度来看,这是一种更准确的方法。
代码
fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)
结果
https://stackoverflow.com/questions/18195758
复制相似问题