matplotlib使用线剪辑图像

2024-05-16 18:47:31 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以将imshow()生成的图像剪辑到一行/多行下的区域?我认为Clip an image using several patches in matplotlib可能有解决方案,但我不确定如何在这里应用它。在

我只想在这个图中的线条下面加上颜色(来自imshow()): Normalized Planck's law plot with IR/Vis/UV coloring

这是我的绘图代码:

from __future__ import division
from matplotlib.pyplot import *
from numpy import *

# wavelength array
lambd = logspace(-3.8, -7.2, 1000)

# temperatures
T_earth = 300
T_sun = 6000

# planck's law constants
h = 6.626069e-34
c = 2.997925e8
k = 1.380648e-23

# compute power using planck's law
power_earth = 2*h*c**2/lambd**5 * 1/(exp(h*c/(lambd*k*T_earth)) - 1)
power_sun = 2*h*c**2/lambd**5 * 1/(exp(h*c/(lambd*k*T_sun)) - 1)

# set up color array based on "spectrum" colormap
colors = zeros((1000,1000))
colors[:,:1000-764] = 0.03
for x,i in enumerate(range(701,765)):
    colors[:,1000-i] = 1-x/(765-701)
colors[:,1000-701:] = 0.98

figure(1,(4,3),dpi=100)
# plot normalized planck's law graphs
semilogx(lambd, power_earth/max(power_earth), 'b-', lw=4, zorder=5); hold(True)
semilogx(lambd, power_sun/max(power_sun), 'r-', lw=4, zorder=5); hold(True)
# remove ticks (for now)
yticks([]); xticks([])
# set axis to contain lines nicely
axis([min(lambd), max(lambd), 0, 1.1])
# plot colors, shift extent to match graph
imshow(colors, cmap="spectral", extent=[min(lambd), max(lambd), 0, 1.1])
# reverse x-axis (longer wavelengths to the left)
ax = gca(); ax.set_xlim(ax.get_xlim()[::-1])

tight_layout()
show()

Tags: tofromimportaxmaxsunpowercolors
1条回答
网友
1楼 · 发布于 2024-05-16 18:47:31

在这种情况下,可以使用曲线下的区域作为面片来应用“设置剪辑路径”。您需要做的就是调用fill_between并提取相应的路径,如下所示:

semilogx(lambd, power_earth/max(power_earth), 'b-', lw=4, zorder=5)
# Area under the curve
fillb_earth = fill_between(lambd, power_earth/max(power_earth), color='none', lw=0)
# Get the path
path_earth, = fillb_earth.get_paths()
# Create a Patch
mask_earth = PathPatch(path_earth, fc='none')
# Add it to the current axes
gca().add_patch(mask_earth)
# Add the image
im_earth = imshow(colors, cmap="spectral", extent=[min(lambd), max(lambd), 0, 1.1])
# Clip the image with the Patch
im_earth.set_clip_path(mask_earth)

然后对太阳重复同样的线条。这是结果。Clipped image

相关问题 更多 >