Aspect ratio in subplots with various y-axes

前端 未结 3 1853
长发绾君心
长发绾君心 2020-12-06 02:50

I would like the following code to produce 4 subplots of the same size with a common aspect ratio between the size of x-axis and y-axis set by me. Referring to the below exa

3条回答
  •  一整个雨季
    2020-12-06 03:16

    The theory

    Different coordinate systems exists in matplotlib. The differences between different coordinate systems can really confuse a lot of people. What the OP want is aspect ratio in display coordinate but ax.set_aspect() is setting the aspect ratio in data coordinate. Their relationship can be formulated as:

    aspect = 1.0/dataRatio*dispRatio
    

    where, aspect is the argument to use in set_aspect method, dataRatio is aspect ratio in data coordinate and dispRatio is your desired aspect ratio in display coordinate.

    The practice

    There is a get_data_ratio method which we can use to make our code more concise. A work code snippet is shown below:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, axes = plt.subplots(nrows=2, ncols=2)
    
    dispRatio = 0.5
    for i, ax in enumerate(axes.flat, start=1):
        ax.plot(np.arange(0, i * 4, i))
        ax.set(aspect=1.0/ax.get_data_ratio()*dispRatio, adjustable='box-forced')
    
    plt.show()
    

    I have also written a detailed post about all this stuff here.

提交回复
热议问题