使用非整数 alpha 值使 matplotlib png 图半透明

make matplotlib png plot semi-transparent with non integer alpha value

我知道我可以生成具有透明背景的 png 图 in the following way(这对我有用):

import matplotlib.pyplot as plt
plt.plot ([1,2,3],[2,1,3])
plt.savefig("test.png",transparent=True)

但是我怎样才能使背景半透明,并带有小数 alpha 数字?我在一个单独的博客上读到可以这样做:

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3]) 
ax.patch.set_facecolor('white')
ax.patch.set_alpha(0.5)
plt.savefig('test.png', facecolor=fig.get_facecolor(), edgecolor='none')

但这对我不起作用并且产生了不透明的情节 并给了我这个不透明的png(在ppt中确认)。

回应评论,

plt.get_backend()

给我 'MacOSX' 我在

Python 3.9.4 (default, Apr 5 2021, 01:49:30) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin

您的代码运行正确,没有任何错误。我在 colab 上试过,结果如下(注意 ax.patch.set_alpha() 值):

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3]) 
ax.patch.set_facecolor('white')
ax.patch.set_alpha(1)
plt.savefig('test.png', facecolor=fig.get_facecolor(), edgecolor='none')

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3]) 
ax.patch.set_facecolor('white')
ax.patch.set_alpha(0)
plt.savefig('test.png', facecolor=fig.get_facecolor(), edgecolor='none')


已更新: 保存绘图后,您可以使用 opencv 加载它,然后像这样更改其透明度:

"""
pip install opencv-python
"""
import cv2

im = cv2.imread('test.png',cv2.IMREAD_UNCHANGED)
im[:,:,3] = im[:,:,3]/2
cv2.imwrite('adjust.png',im)

更新二: 我想我找到了你想要的:

import matplotlib.pyplot as plt
import numpy as np
import cv2

fig,ax=plt.subplots()
ax.plot ([1,2,3],[2,1,3]) 
ax.patch.set_facecolor('white')
plt.savefig('original.png', edgecolor='none')
plt.savefig('transparent.png', edgecolor='none',transparent=True)
#Then
im = cv2.imread('original.png',cv2.IMREAD_UNCHANGED)
im[:,:,3] = im[:,:,3]/2 + 120
cv2.imwrite('semi_transparent.png',im)

这是我得到的结果(在 MS word 上测试):