簡體   English   中英

將圖像添加到繪圖-matplotlib PYTHON

[英]Adding image to a plot -matplotlib PYTHON

我正在嘗試在圖的右側插入.png圖像,並按照此處提到的代碼進行操作: 使用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')

熱圖將在左側,而樹的圖像將插入在右側。 有了上面的代碼,這就是我得到的...

圖片未正確添加:-----

這是我要添加的圖像:----

右側添加了一些內容,但顯然並非如此。 起初我以為我將phyl_ax的尺寸設置得太小,但是當我嘗試增大它時,甚至也沒有添加以前的“內容”。

有人可以指出我要去哪里哪里嗎?

您要同時調用兩個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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM