简体   繁体   中英

Set size of subplot to other sublot with equal aspect ratio

I would like a representation consisting of a scatter plot and 2 histograms on the right and below the scatter plot create. I have the following requirements: 1.) In the scatter plot, the apect ratio is equal so that the circle does not look like an ellipse. 2.) In the graphic, the subplots should be exactly as wide or high as the axes of the scatter plot.

This also works to a limited extent. However, I can't make the lower histogram as wide as the x axis of the scatter plot. How do I do that?

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import random

#create some demo data 
x = [random.uniform(-2.0, 2.0) for i in range(100)]
y = [random.uniform(-2.0, 2.0) for i in range(100)]

#create figure
fig = plt.figure()


gs = gridspec.GridSpec(2, 2, width_ratios = [3, 1], height_ratios = [3, 1])
ax = plt.subplot(gs[0])

# Axis labels
plt.xlabel('pos error X [mm]')
plt.ylabel('pos error Y [mm]')
ax.grid(True)
ax.axhline(color="#000000")
ax.axvline(color="#000000")
ax.set_aspect('equal')

radius = 1.0
xc = radius*np.cos(np.linspace(0,np.pi*2))
yc = radius*np.sin(np.linspace(0,np.pi*2))
plt.plot(xc, yc, "k")

ax.scatter(x,y)

hist_x = plt.subplot(gs[1],sharey=ax)
hist_y = plt.subplot(gs[2],sharex=ax)


plt.tight_layout() #needed. without no xlabel visible

plt.show()

结果是

what i want is:

在此处输入图片说明

Many thanks for your help!

The easiest (but not necessarily most elegant) solution is to manually position the lower histogram after applying the tight layout:

ax_pos = ax.get_position()
hist_y_pos = hist_y.get_position()
hist_y.set_position((ax_pos.x0, hist_y_pos.y0, ax_pos.width, hist_y_pos.height))

matplotlib 3.4.3 的输出

This output was produced by matplotlib version 3.4.3. For your example output, you're obviously using a different version, as I get a much wider lower histogram than you.

(I retained the histogram names as in your example although I guess the lower one should be hist_x instead of hist_y ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM