在matplotlib

时间:2018-05-02 21:50:34

标签: python matplotlib axes

我正在尝试对齐这些图,以便顶部图的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()

output

1 个答案:

答案 0 :(得分:0)

我建议使用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()

enter image description here