【问题标题】:Matplotlib: Same height for subfiguresMatplotlib:子图的高度相同
【发布时间】:2015-05-20 23:24:45
【问题描述】:

在以下示例中,如何将两个子图设置为相同的高度?

#minimal example
import matplotlib.pyplot as plt
import numpy as np
f, (ax1, ax2) = plt.subplots(1, 2)
im = np.random.random((100,100))
ax1.imshow(im)
ax1.set_xlim(0, im.shape[1])
ax1.set_ylim(0, im.shape[0])
x = np.arange(100)
ax2.plot(x, x**2)

【问题讨论】:

    标签: python matplotlib subplot imshow


    【解决方案1】:

    你可以使用matplotlib.gridspec:

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    import numpy as np
    
    # Add subplots using gridspec instead of plt.subplots()
    gs = gridspec.GridSpec(1,2, height_ratios=[1,1])
    f = plt.figure()
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    
    im = np.random.random((100,100))
    ax1.imshow(im)
    ax1.set_xlim(0, im.shape[1])
    ax1.set_ylim(0, im.shape[0])
    x = np.arange(100)
    ax2.plot(x, x**2)
    

    产生如下输出:

    【讨论】:

    • 这在我的机器上失败了:ValueError: Expected the given number of height ratios to match the number of rows of the grid(在 GridSpec 构造函数中)
    猜你喜欢
    • 2016-10-12
    • 2014-11-20
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2017-03-01
    相关资源
    最近更新 更多