如何用python在两个直方图的子图中设置距离
时间: 2024-06-03 07:08:16 浏览: 10
可以使用`gridspec`来设置子图的位置和大小,并利用`wspace`参数来设置两个子图之间的水平距离。
以下是一个示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# 生成数据
np.random.seed(42)
data1 = np.random.normal(loc=0.0, scale=1.0, size=1000)
data2 = np.random.normal(loc=1.0, scale=2.0, size=1000)
# 创建画布和子图
fig = plt.figure(figsize=(8, 4))
gs = GridSpec(1, 2, width_ratios=[2, 1]) # 一行两列,第一列宽度为第二列的两倍
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])
# 绘制直方图
ax1.hist(data1, bins=20, alpha=0.5, color='blue')
ax2.hist(data2, bins=20, alpha=0.5, color='green')
# 设置子图距离
plt.subplots_adjust(wspace=0.3)
# 显示图像
plt.show()
```
输出结果如下图所示:
![histogram_subplots](https://user-images.githubusercontent.com/38177254/136693798-8d232e34-22d9-4c1c-9d8a-165663f13c0e.png)