如何使用Matplotlib的Gridspec来拟合/调整大小/屏蔽图像以适合(精确)在列单元格内?
下面的代码需要一个软糖因子53来调整图像大小以适合(确切地)在单元格内。
import matplotlib.gridspec as gridspec
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
%config InlineBackend.figure_formats = {'png', 'retina'}
%matplotlib inline
side = 10
nrows=5
ncols =5
fudge = 53
fig = plt.figure(figsize=(15, 15))
gs = gridspec.GridSpec(nrows=5, ncols=5, wspace=0, hspace=0,
width_ratios=[1,1,1,1,1],
height_ratios=[1,1,1,1,1])
axes = {}
######################
# Thumbnail Image Column
for i in range(0,nrows):
axes[i] = plt.subplot(gs[i,0])
axes[i].set_xlim(0,10)
axes[i].set_ylim(0,10)
axes[i].axis("on")
# Add Grey Square
square = plt.Rectangle((0, 0), side, side, fc='b', hatch='///', linewidth=1, color='grey' )
axes[i].add_patch(square)
bbox = axes[i].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
width *= fig.dpi *2
height *= fig.dpi*2
print(width,height, fig.dpi)
#print(fig.dpi, bbox.width, width, bbox.height, height)
# Trying to Mask/Resize the Image so it fits within the Column Cell
img = Image.open("./images/test_500x500_pixel.png")
#img_crop = img.crop((0, 0 ,width, height)) # Not using crop
img.thumbnail((width+fudge, height+fudge), Image.ANTIALIAS)
imagebox = OffsetImage(img, zoom=1, alpha=1)
ab = AnnotationBbox(imagebox, xy=(0,0),
xycoords='data',
frameon=False,
box_alignment=(0,0),
boxcoords = None,
pad=0.0
)
axes[i].add_artist(ab)
plt.tight_layout(pad=0)
我试图让图像适合列单元格 - 无论图形大小如何。此列包含缩略图图像。其他列是从python pandas数据帧中提取的数据。
非常感谢提前。
答案 0 :(得分:1)
以下非常简单的代码为image列提供了相同的宽高比。
import numpy as np
import matplotlib.pyplot as plt
image = plt.imread("https://i.stack.imgur.com/ltBO1.png")
N = 5
fig, ax = plt.subplots(N,2, figsize=(5,8))
for i in range(N):
thisimage = np.copy(image)
thisimage[:,:,0] = thisimage[:,:,0]*(i+1)/float(N)
ax[i,0].imshow(thisimage)
ax[i,0].set_xticks([])
ax[i,0].set_yticks([])
ax[i,1].plot(np.random.rand(9))
plt.show()
我不清楚这有多远不符合要求?