从一个已经存在的matplotlib图开始,我通过在底部附加一个小轴来添加一个页脚.我们的 idea 是用任意数量的徽标填充这个页脚.我想把标志并排(由用户控制垫参数分开),使他们填补了页脚的高度,从而计算其宽度,以保持锁定的纵横比.
这是一个独立的MRE,总结了我的方法
from matplotlib.image import imread as read_png
import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
fig = plt.figure(1, figsize=(6, 6))
ax = plt.gca()
ax.set_axis_off()
X, Y = np.meshgrid(np.linspace(-3.0, 3.0, 100),
np.linspace(-2.0, 2.0, 100))
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
z = Z1 * 30 + 50 * Z2
cs = ax.contourf(X, Y, z, cmap='PuBu_r')
ax_divider = make_axes_locatable(ax)
ax_footer = ax_divider.append_axes(
"bottom", size="10%", pad=0.1)
ax_footer.set_axis_off()
def add_logo(ax, logo, zoom, pos):
img_logo = OffsetImage(read_png(logo), zoom=zoom)
logo_ann = AnnotationBbox(
img_logo, pos, xycoords='axes fraction',
frameon=False, box_alignment=(0, 0.25))
at = ax.add_artist(logo_ann)
return at
add_logo(ax_footer,
cbook.get_sample_data('grace_hopper.jpg'),
zoom=0.07,
pos=(0, 0))
add_logo(ax_footer,
cbook.get_sample_data('grace_hopper.jpg'),
zoom=0.07,
pos=(0.2, 0))
plt.show()
它产生了
然而,我必须明确地设置zoom
和pos
,以便数字占据正确的空间.
有没有一种方法可以自动计算这些参数,使数字自动放置在彼此旁边,他们填补页脚轴?或者也许有更好的方法?
我看到了许多定义带有不同行和列的子图来放置图形的示例,但我已经有了轴.我还没有找到任何方法来将已经存在的轴分割成相同宽度的任意数量的插入轴.
-编辑
在Jody Klymak令人惊叹的回答的基础上展开,这是我的最终版本.一旦你有了一个通用的轴来放置徽标(我仍然使用make_axes_locatable
和append_axes
),你就可以使用这个函数了
def add_logos(ax, logos, x_padding=10):
left = 0
for _, logo in enumerate(logos):
imdata = read_png(logo)
w = imdata.shape[1]
h = imdata.shape[0]
ax.imshow(imdata,
extent=[left, left + w, 0, h])
left = left + w + x_padding
# set the limits, otherwise the focus in on the last image
ax.set_xlim(0, left)
ax.set_ylim(0, h)
# anchor the fixed aspect-ratio axes on the left.
ax.set_anchor('W')
用作
add_logos(ax_footer, ["../input/logos/Logonuovo.png",
"../input/logos/earth_networks_logo.png"])