Text or legend cut from matplotlib figure on savefig()

后端 未结 2 1844
礼貌的吻别
礼貌的吻别 2020-12-31 07:53

Say I want to plot a very simple figure with 2-subplot laid out horizontally, and I want to add some text on the right of the second subplot. I am working in Jupyter Noteboo

相关标签:
2条回答
  • 2020-12-31 08:34

    Jupyter notebook is by default configured to use its "inline" backend (%matplotlib inline). It displays a saved png version of the figure. During this saving, the option bbox_inches="tight" is used.

    In order to replicate the figure that you see in the jupyter output, you would need to use this option as well.

    plt.savefig("output.png", bbox_inches="tight")
    

    What this command does is to extend or shrink the area of the saved figure to include all the artists in it.

    Alternatively, you can shrink the content of the figure, such that there is enough space for the text to fit into the original figure.

    This can be done with e.g.

    plt.subplots_adjust(right=0.7)
    

    which would mean that the rightmost axes stops at 70% of the figure width.

    0 讨论(0)
  • 2020-12-31 08:41

    Adding bbox_inches="tight" to the savefig **kwargs will do it:

    plt.savefig(r'C:\mypy\test_graph.png', ext='png', bbox_inches="tight")  
    

    Saved file:

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