python - matplotlib 图形中的白色到透明层 (SVG)

标签 python matplotlib svg python-imaging-library transparency

我想在我的 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)

结果应如下所示:
之前:
Before
之后:
After

最佳答案

要实现过渡效果,您可以使用双三次插值和自定义颜色图在现有图形的顶部绘制一层。
首先,您必须创建只有两种颜色的颜色图。
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/

相关文章:

python - 为什么 Python 的多处理模块中没有 Timer 类?

python - 如何在 matplotlib 中用日期字符串交换 x 刻度

python - 使用 Matplotlib 和 Numpy,有没有办法找到线性方程的所有直线交点?

html - 停止时 SGV 梯度变暗

javascript - 不使用鼠标滚轮缩小 D3 力导向图

html - 在不添加笔划的情况下为虚线边框设置动画

python - 使用 Python 和 pyathenajdbc 连接 Athena

python - 如何在python docx模板(docxtpl)中显示图像? python

python - Plotly 中的水平条形图使用带有 2 条迹线的袖扣

python - 如何在水平条形图中绘制计数器对象?