简体   繁体   English

将子图的大小设置为具有相同纵横比的其他子图

[英]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.我想要一个由散点图和散点图右侧和下方的 2 个直方图组成的表示。 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.我有以下要求: 1.) 在散点图中,纵横比相等,因此圆看起来不像椭圆。 2.) In the graphic, the subplots should be exactly as wide or high as the axes of the scatter plot. 2.) 在图形中,子图应与散点图轴的宽度或高度完全相同。

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.但是,我不能使下直方图与散点图的 x 轴一样宽。 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.此输出由 matplotlib 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 ). (我保留了您的示例中的直方图名称,尽管我猜较低的名称应该是hist_x而不是hist_y )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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