matplotlib - 使用线条剪辑图像

时间:2013-02-20 18:15:15

标签: python matplotlib

是否可以将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()

1 个答案:

答案 0 :(得分:3)

在这种情况下,您可以使用曲线下的区域作为修补程序来应用set_clip_path。您所要做的就是调用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