将图像添加到绘图-matplotlib PYTHON

时间:2014-02-28 21:37:47

标签: python image matplotlib heatmap

我正在尝试将.png图像插入到图的右侧,并按照此处提到的代码进行操作: Combine picture and plot with Python Matplotlib

以下是我的尝试:

import numpy as np
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.cbook as cbook
from matplotlib._png import read_png
from matplotlib.offsetbox import OffsetImage 
cmap = mpl.cm.hot
norm = mpl.colors.Normalize(vmin=-1 * outlier, vmax=outlier)
cmap.set_over('green')
cmap.set_under('green')
cmap.set_bad('green')
plt.xlim(0,35)
plt.ylim(0,35)
fig, ax = plt.subplots()
ax.set_aspect('equal')
cb_ax=fig.add_axes([0.85, 0.1, 0.03, 0.8])
img = ax.imshow(np.ma.masked_values(data, outlier), cmap=cmap, norm=norm, interpolation='none',vmax=outlier)
cb = mpl.colorbar.ColorbarBase(cb_ax, cmap=cmap, norm=norm, extend='both')
##axim = plt.subplot2grid(shape, loc, rowspan=1)

## phlo tree
image_file = cbook.get_sample_data('mytree.png',asfileobj=False)
image = plt.imread(image_file)
phyl_ax=fig.add_axes([0.10,0.1, 0.03, 0.8])
phyl_ax.imshow(image,interpolation='nearest')

热图将位于左侧,树的图像将插入右侧。以上代码就是我得到的......

Image not added properly:-----

Here is the image I am trying to add:----

右侧有一些东西,但显然不是它的样子。 起初我以为我将phyl_ax的尺寸设置得太小但是当我试图增加它时,即使是之前的“东西”也没有添加。

有人能指出我出错的地方吗?

1 个答案:

答案 0 :(得分:1)

您正在调用subplots,默认情况下,它会为您提供单个轴,并通过add_axes添加轴。你应该做其中一个,例如

...
fig = plt.figure()
ht_ax = fig.add_axes([0.1, 0.1, 0.3, 0.8])
cb_ax = fig.add_axes([0.45, 0.3, 0.02, 0.4])
phyl_ax = fig.add_axes([0.6, 0.1, 0.3, 0.8])

...

- 或 -

...
fig, ax = plt.subplots(1,2)
fig.subplots_adjust(left=0.15)
ht_ax = ax[0]
phyl_ax = ax[1]
cb_ax=fig.add_axes([0.05, 0.3, 0.02, 0.4])

...

您可以使用subplots_adjustset_aspect来调整布局。您还可以使用colorbar.make_axes来获得适当大小的颜色条轴。在这里,我还使用了grid_spec来获得我喜欢的大小比例

gs = gridspec.GridSpec(1, 2, width_ratios=[3, 2]) 
ht_ax = plt.subplot(gs[0])
phyl_ax = plt.subplot(gs[1])
cb_ax, kw = mpl.colorbar.make_axes(ht_ax, shrink=0.55)
...
cb = mpl.colorbar.ColorbarBase(ax=cb_ax, cmap=cmap, norm=norm, extend='both', **kw)