首页 > 解决方案 > 如何在彼此之上创建 2 个具有相同 x 轴和不同 y 轴的图形?

问题描述

所以说我有正确格式的数据,用于颜色图顶部的折线图。我将如何像下面在 Python 中看到的那样堆叠它们,它们都具有相同的 x 轴但不同的 y 轴?

谢谢

在此处输入图像描述

标签: pythonpython-3.x

解决方案


您可以使用plt.subplots和适当的参数设置您的轴(特别注意gridspec_kw参数)。

你想要类似的东西

gridspec_kw = dict(
    # Defines the heights of the two plots 
    # (bottom plot twice the size of the top plot)
    height_ratios=(1, 2),  
    # Zero space between axes
    hspace=0,
)

# Setup the figure with 2 rows, sharing the x-axis and with 
# the gridspec_kw arguments defined above
fig, axes = plt.subplots(
    nrows=2, ncols=1, sharex=True, 
    gridspec_kw=gridspec_kw,
)

完整示例:

import numpy as np 
import matplotlib.pyplot as plt 

x = np.random.normal(size=10_000)
y = np.random.uniform(size=10_000)


gridspec_kw = dict(
    height_ratios=(1, 2),
    hspace=0,
)

fig, axes = plt.subplots(
    nrows=2, ncols=1, sharex=True, gridspec_kw=gridspec_kw,
)

axes[0].hist(x)
axes[1].hist2d(x, y)

plt.show()

会给你

在此处输入图像描述


推荐阅读