How to disable bbox_inches='tight' when working with matplotlib inline in ipython notebook

后端 未结 2 779
悲哀的现实
悲哀的现实 2021-01-05 22:44

When work with matplotlib inline backend in ipython notebook, the default behavior is using bbox_inches=\'tight\' to generate the embedded png image internally via savefig()

相关标签:
2条回答
  • 2021-01-05 23:16

    You may use pyplot.subplots to align the plots in a grid order, so the figures will be visually aligned in notebook (if that's what you want?)

    Something like this:

    %matplotlib inline
    import matplotlib.pyplot as plt
    import numpy as np
    
    d1 = np.random.rand(100)
    d2 = np.random.rand(100)*10000
    
    fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
    plt.subplots_adjust(left=0.2)
    ax1.plot(d1)
    ax2.plot(d2)
    

    Updates

    As OP's requirements to use separate plots rather than subplots, here is a hacky solution. This is working on my Notebook, more details about the customization can be found HERE.

    import matplotlib.pyplot as plt
    import numpy as np
    
    %matplotlib inline
    
    # to override ytick.major.width before any plot
    plt.rcParams['ytick.major.pad'] = 20
    plt.plot(np.random.rand(100))
    
    # another override to set alignment for the plot 
    plt.rcParams['ytick.major.pad'] = 5
    plt.figure()
    plt.plot(np.random.rand(100)*10000)
    

    The Plots

    # plt.rcdefaults() will reset everything to defaults as the doc says.
    

    Not the most elegant way but it's working as required.

    0 讨论(0)
  • 2021-01-05 23:29

    There's a fuller answer here: Matplotlib and Ipython-notebook: Displaying exactly the figure that will be saved

    The trick is to turn off the bbox_inches='tight' setting in ipython. It's a bit awkward to do temporarily, but just run the IPython magic in a block: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}

    If you want to switch back to the normal way, where axis labels are automatically never cut, you can run %config InlineBackend.print_figure_kwargs = {'bbox_inches':'tight'} but it has to be after the block where you do the plotting that needs precise bounding boxes.

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