我正在尝试将并排的numpy数组显示为同一阵列的图像和seaborn distplot。我想出了以下功能:
def visualize(arr):
f, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios': [1, 3]})
ax1.imshow(arr)
flat = arr.flatten()
x = flat[~np.isnan(flat)]
sns.distplot(x, ax=ax2)
plt.show()
如您所见,图像的高度小于图表。如何修改我的功能,以便为绘图和imshow提供相同的高度?
答案 0 :(得分:1)
有很多方法可以解决这个问题。以下所有内容将提供或多或少相同的图像
您可以减少可用空间,使两个图都限制在相同的垂直边距。这可以通过
来完成降低身材高度
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6,2.3), ...)
使用subplots_adjust
来限制边距
fig.subplots_adjust(top=0.7, bottom=0.3)
InsetPosition
您可以使用mpl_toolkits.axes_grid1.inset_locator.InsetPosition
调整第二个轴的坐标以匹配第一个轴的坐标。
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
def visualize(arr):
fig, (ax1, ax2) = plt.subplots(1, 2,
gridspec_kw = {'width_ratios': [1, 3]})
ax1.imshow(arr)
flat = arr.flatten()
x = flat[~np.isnan(flat)]
sns.distplot(x, ax=ax2)
ip = InsetPosition(ax1, [1.5,0,3,1])
ax2.set_axes_locator(ip)
plt.show()
arr = np.random.randn(200,120)
visualize(arr)
您可以只为图像创建轴,然后使用mpl_toolkits.axes_grid1.make_axes_locatable
在其旁边创建新轴。
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
def visualize(arr):
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
ax2 = divider.new_horizontal(size="300%", pad=0.5)
fig.add_axes(ax2)
ax.imshow(arr)
flat = arr.flatten()
x = flat[~np.isnan(flat)]
sns.distplot(x, ax=ax2)
plt.show()
arr = np.random.randn(200,120)
visualize(arr)
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
def visualize(arr):
gkw = {'width_ratios':[1, 3] }
fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = gkw )
ax1.imshow(arr)
flat = arr.flatten()
x = flat[~np.isnan(flat)]
sns.distplot(x, ax=ax2)
ya = np.diff(np.array(ax2.get_ylim()))[0]
xa = np.diff(np.array(ax2.get_xlim()))[0]
wa = gkw['width_ratios'][0]/float(gkw['width_ratios'][1])
ia = arr.shape[0]/float(arr.shape[1])
ax2.set_aspect(float(wa*ia/(ya/xa)))
plt.show()
arr = np.random.randn(200,120)
visualize(arr)
您可以获得左图的位置并将其y坐标复制到右侧子图的位置。这是对现有代码的一个很好的附加组件。缺点是必要的,因为随后对图形大小的更改需要重新计算位置。
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
def visualize(arr):
gkw = {'width_ratios':[1, 3] }
fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = gkw )
ax1.imshow(arr)
flat = arr.flatten()
x = flat[~np.isnan(flat)]
sns.distplot(x, ax=ax2)
def on_resize(evt=None):
ax1.apply_aspect()
bb1 = ax1.get_position()
bb2 = ax2.get_position()
bb2.y0 = bb1.y0; bb2.y1 = bb1.y1
ax2.set_position(bb2)
fig.canvas.mpl_connect("resize_event", on_resize)
on_resize()
plt.show()
arr = np.random.randn(200,120)
visualize(arr)