Matplotlib: Getting subplots to fill figure

前端 未结 3 1429
囚心锁ツ
囚心锁ツ 2020-12-11 17:35

I would please like suggestions for how to override the default matplotlib behaviour when plotting images as subplots, whereby the subplot sizes don\'t seem to match the fig

3条回答
  •  粉色の甜心
    2020-12-11 17:51

    First, you're using calls to plt when you have Axes objects as your disposal. That road leads to pain. Second, imshow sets the aspect ratio of the axes scales to 1. That's why the axes are so narrow. Knowing all that, your example becomes:

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.random.rand(10,4)
    
    #creating a wide figure with 2 subplots in 1 row
    fig, axes = plt.subplots(1, 2, figsize=(9,3))  
    
    for ax in axes.flatten():  # flatten in case you have a second row at some point
        img = ax.imshow(data, interpolation='nearest')
        ax.set_aspect('auto')
    
    plt.colorbar(img)
    

    On my system, that looks like this: enter image description here

提交回复
热议问题