简体   繁体   中英

How can would I create 2 graphs on top of each other with both having the same x-axis and different y-axis?

So say I have the data in the right format for a line graph on top of a colour map. How would I go about stacking them like seen below in Python with them both having the same x-axis but different y-axis?

Thanks

在此处输入图片说明

You can setup your axes like that using plt.subplots and the appropriate arguments (paying special attention to the gridspec_kw argument).

You want something like

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,
)

Full example:

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()

will give you

在此处输入图片说明

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