首页 > 解决方案 > 在matplotlib中对齐不同图的轴

问题描述

我正在尝试对齐这些图,以便顶部图的 x 轴与 imshow 的 x 轴值完全对齐。我可以通过将方面设置为自动来做到这一点,但是我的图像被扭曲了。有没有办法做到这一点?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 1200)
y = np.linspace(-20, 20, 1600)
xv, yv = np.meshgrid(x, y)
w = 3
xpos = 0
ypos = 5
z = np.exp(-((xv - xpos)**2 + (yv - ypos)**2) / w**2)
xh = np.linspace(0, 2)
yh = np.sin(xh)

sumvertical = np.sum(z, 0)
xvert = range(np.shape(z)[1])

sumhoriz = np.sum(z, 1)
yhoriz = range(np.shape(z)[0])

# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02

rect_scatter = [left, bottom, width, height]
rect_x = [left, bottom_h, width, 0.2]
rect_y = [left_h, bottom, 0.2, height]

plt.figure(1, figsize=(8, 8))

axCenter = plt.axes(rect_scatter)
axhoriz = plt.axes(rect_x)
axvert = plt.axes(rect_y)

axCenter.imshow(z, origin='lower', cmap='jet') #aspect='auto')
axhoriz.plot(xvert, sumvertical)
axvert.plot(sumhoriz, yhoriz)

plt.show()

输出

标签: pythonmatplotlibaxes

解决方案


我建议使用 中的工具mpl_toolkits.axes_grid1,即make_axes_locatable划分中心轴以为边缘轴留出空间。

margins然后,您还应该沿共享方向将设置为 0 以使范围匹配。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

x = np.linspace(-10, 10, 1200)
y = np.linspace(-20, 20, 1600)
xv, yv = np.meshgrid(x, y)
w = 3
xpos = 0
ypos = 5
z = np.exp(-((xv - xpos)**2 + (yv - ypos)**2) / w**2)
xh = np.linspace(0, 2)
yh = np.sin(xh)

sumvertical = np.sum(z, 0)
xvert = range(np.shape(z)[1])

sumhoriz = np.sum(z, 1)
yhoriz = range(np.shape(z)[0])


fig, axCenter = plt.subplots(figsize=(8, 8))
fig.subplots_adjust(.05,.1,.95,.95)

divider = make_axes_locatable(axCenter)
axvert = divider.append_axes('right', size='30%', pad=0.5)
axhoriz = divider.append_axes('top', size='20%', pad=0.25)

axCenter.imshow(z, origin='lower', cmap='jet')
axhoriz.plot(xvert, sumvertical)
axvert.plot(sumhoriz, yhoriz)

axhoriz.margins(x=0)
axvert.margins(y=0)

plt.show()

在此处输入图像描述


推荐阅读