Skip to content

[Python] Matplotlib 繪圖時去白邊的問題

Matplotlib 是 Python 中相當著名的繪圖套件,也是所有使用 Python 進行資訊視覺化的人一定會接觸到的工具之一。不過每次在我使用 matplotlib 進行繪圖的時候,有時候會苦惱於繪製出的圖形有著多餘的『白框』的問題,對我而言是不太美觀的。

舉個例子吧,今天我有一張叫做 “test.png” 的照片。

那麼,如果我使用 matplotlib 讀取、並且繪製出呢?

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = mpimg.imread('test.png')
plt.imshow(image)
plt.show()



Output:

不過由於我的 Blog 底色是白色的,所以可能看不太出來:這張圖片的上下左右,全都多出了白色的邊框,老實說,這是會影響展示效果的。


去除白色邊框的方法

這裡分享一個在 stackoverflow 上查到的辦法,我覺得效果挺棒的。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = mpimg.imread('test.png')
plt.axis('off')

fig = plt.imshow(image, interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

plt.savefig('test_output.png',
            bbox_inches='tight',
            pad_inches=0,
            format='png',
            dpi=300)



Output:

不過這個方法是將圖片儲存下來,我在使用 plt.show() 的時候圖片仍然存在著白色邊框。當然,這是個小問題,如果真的是想要展示效果,只要使用 PIL 之類的模組顯示出來即可。

比如說:

image = Image.open('test_output.png')
image.show()



References

Leave a Reply