我想在我的 matplotlib 图像顶部添加一个带有渐变(从白色到透明)的图层,并最终能够将结果保存为 SVG(我的实际图像上的形状比下面绘制的形状更多) .
我不清楚 matplotlib + svg 是否可以做到这一点。有谁知道或有解决方案吗?
这里是一些示例代码:
plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
# TODO: Add white -> transparent layer
plt.savefig("temp.svg", bbox_inches=0)
最佳答案
要实现过渡效果,您可以使用双三次插值和自定义颜色图在现有图形的顶部绘制一层。
首先,您必须创建只有两种颜色的颜色图。
alpha channel = 0 的白色和 alpha channel = 1 的其他白色。
然后我们添加另一个从上到下填充新颜色图的图形。
这是执行此操作的代码:
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1 * np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
# Add new subplot on top of what is there already
ax = fig.add_subplot()
ax.axis('off')
ax.set_position([0, 0, 1, 1])
# Create colormap of two white colors, one with alpha=0 and other one with alpha=1
colors = [(1, 1, 1, 0), (1, 1, 1, 1)]
# Create new colormap from our two colors
cmap = mcolors.LinearSegmentedColormap.from_list('mycmap', colors)
# Use imshow with bicubic interpolation to create transition from top to bottom
ax.imshow([[0., 0.], [1., 1.]],
cmap=cmap, interpolation='bicubic', aspect='auto'
)
# Save as .svg file
plt.savefig("temp.svg", bbox_inches=0)
关于python - matplotlib 图形中的白色到透明层 (SVG),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70977778/