How to export plots from matplotlib with transparent background?

前端 未结 2 1106
一生所求
一生所求 2020-12-07 13:49

I am using matplotlib to make some graphs and unfortunately I cannot export them without the white background.

<script

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 14:16

    Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

    In [30]: x = np.linspace(0,6,31)
    
    In [31]: y = np.exp(-0.5*x) * np.sin(x)
    
    In [32]: plot(x, y, 'bo-')
    Out[32]: []            
    
    In [33]: savefig('demo.png', transparent=True)
    

    Result: demo.png

    Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

    display screenshot

提交回复
热议问题