2014-02-28 48 views
1

我試圖插入一個PNG圖片的情節的右側,這裏提到的代碼如下: Combine picture and plot with Python Matplotlib將圖片添加到情節-matplotlib PYTHON

這裏是我曾嘗試:

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') 

Th熱圖將在左側,樹的圖像將插入右側。這裏與上面的代碼是什麼我得到...

Image not added properly:-----

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

沒有被添加到右側的東西,但顯然它是不是應該像的方式。 起初我以爲我設置phyl_ax的尺寸太小,但是當我嘗試增加它時,即使之前的「東西」也沒有被添加。

有人能指出我出錯的地方嗎?

回答

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) 
+0

對不起,我需要一個小的澄清。有一個軸用於熱圖的imshow,所以根據您的第一個解決方案,我應該在使用它之前添加此軸? – user2998764

+0

是的,看我更新的答案。 – hackyday

+0

Gridspec完美地完成了這個技巧,謝謝 – user2998764