Make identical matplotlib plots with y-axes of different sizes

后端 未结 1 1713
梦谈多话
梦谈多话 2021-01-16 04:16

I am trying to make a series of matplotlib plots that plot timespans for different classes of objects. Each plot has an identical x-axis and plot elements like a title and a

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 04:51

    You can start by defining the margins on top and bottom in units of inches. Having a fixed unit of one data unit in inches allows to calculate how large the final figure should be. Then dividing the margin in inches by the figure height gives the relative margin in units of figure size, this can be supplied to the figure using subplots_adjust, given the subplots has been added with add_subplot.

    A minimal example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = [np.random.rand(i,2) for i in [2,5,8,4,3]]
    
    height_unit = 0.25 #inch
    t = 0.15; b = 0.4  #inch
    
    for d in data:
        height = height_unit*(len(d)+1)+t+b
        fig = plt.figure(figsize=(5, height))
        ax = fig.add_subplot(111)
        ax.set_ylim(-1, len(d))
        fig.subplots_adjust(bottom=b/height, top=1-t/height, left=0.2, right=0.9)
    
        ax.barh(range(len(d)),d[:,1], left=d[:,0], ec="k")
        ax.set_yticks(range(len(d)))
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题