gpt4 book ai didi

python - Matplotlib:具有透明颜色的填充等高线图

转载 作者:太空狗 更新时间:2023-10-29 20:31:22 27 4
gpt4 key购买 nike

有人知道——在 Matplotlib 中——如何用半透明颜色制作好看的填充等高线图吗?如果向 contourf() 传递一个具有半透明颜色的颜色图,它会在填充区域之间产生小间隙:

small gaps between areas

根据docs ,这不是错误(“contourf() [...] 不绘制多边形边”)。要绘制边缘,建议“通过调用 contour() 添加线条轮廓”。但这看起来也不太好,因为边缘变得太不透明了:

edges are too opaque

您可以尝试使用 contour()linewidth 参数,但这并没有太大帮助。有什么想法吗?

这是重现问题的代码(我使用面向对象的 API,但结果与 pyplot 相同):

import matplotlib
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg

# generate some data
shape = (100, 100)
x_rng = np.linspace(-1, 1, shape[1])
y_rng = np.linspace(-1, 1, shape[0])
x, y = np.meshgrid(x_rng, y_rng)
z = np.sqrt(x**2 + y**2)

# create figure
width_inch, height_inch = 5, 5 # results in 500x500px with dpi=100
fig = Figure()
fig.set_size_inches((width_inch, height_inch))
FigureCanvasAgg(fig)
ax = fig.add_axes([0., 0., 1., 1.])
ax.set_axis_off()

# define some colors with alpha < 1
alpha = 0.9
colors = [
(0.1, 0.1, 0.5, alpha), # dark blue
(0.0, 0.7, 0.3, alpha), # green
(0.9, 0.2, 0.7, alpha), # pink
(0.0, 0.0, 0.0, alpha), # black
(0.1, 0.7, 0.7, alpha), # light blue
]
cmap = matplotlib.colors.ListedColormap(colors)
levels = np.array(np.linspace(0, z.max(), len(colors)))
norm = matplotlib.colors.BoundaryNorm(levels, ncolors=cmap.N)

# contourf plot produces small gaps between filled areas
cnt = ax.contourf(x, y, z, levels, cmap=cmap, norm=norm,
antialiased=True, linecolor='none')

# this fills the gaps, but it makes them too opaque
# ax.contour(x, y, z, levels, cmap=cmap, norm=norm,
# antialiased=True)

# the same is true for this trick:
# for c in cnt.collections:
# c.set_edgecolor("face")

filename = "/tmp/contourf.png"
fig.savefig(filename, dpi=100, transparent=True, format="png")

PS:相同的情节在 SVG 后端看起来不错。

PPS: pcolormesh() 也有类似的问题:

ax.pcolormesh(x, y, z, cmap=cmap, norm=norm,
edgecolor="face", antialiased=True)

enter image description here

最佳答案

我不知道这是否能解决您的问题,因为“好看”有点主观,但这是在放大到该级别将使用矢量格式,如 SVG、EPS 等(如您所指出的)。

SVG(可缩放矢量图形)

enter image description here

如果关闭抗锯齿,您可以消除边缘模糊和“不透明”,但在高缩放级别时您会看到圆的边缘呈锯齿状。您可以尝试将 dpi 增加到 300dpi,然后另存为 tiff:

Tiff,300dpi,抗锯齿=假

enter image description here

抗锯齿将沿圆边界混合图像,因此混合透明的粉红色和绿色将产生更暗的颜色,这可能给人一种看起来更不透明的印象,即使透明度在理论上是相同的.

通过注释/注释掉您代码的以下部分,我得到了不同的结果,但结果太主观了,无法说哪个更好看:

设置轮廓但不设置边缘颜色:

ax.contour(x, y, z, levels, cmap=cmap, norm=norm,
antialiased=True)

# the same is true for this trick:
# for c in cnt.collections:
# c.set_edgecolor("face")

不设置轮廓,设置边缘颜色:

# ax.contour(x, y, z, levels, cmap=cmap, norm=norm,
# antialiased=True)

# the same is true for this trick:
for c in cnt.collections:
c.set_edgecolor("face")

但它们是否好看取决于解释。我发现的另一件事是我的图像查看器有它自己内置的抗锯齿功能,所以你可能想在尝试进行比较时关闭它。

关于python - Matplotlib:具有透明颜色的填充等高线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com