这是来自Mathematica的示例。
Plot[Abs[Exp[2 I x - x^2/2]], {x, -4, 4}, Filling -> Axis,
FillingStyle -> Automatic,
ColorFunction -> Function[{x, y}, Hue[Rescale[Arg[Exp[2 I x - x^2/2]], {-Pi, Pi}]]],
ColorFunctionScaling -> False]
产生下图
我想在python中进行等效绘制。 matplotlib是否有等效的colorfunction选项?
答案 0 :(得分:2)
这并不像您的Mathematica示例那么优雅,但是以下代码在matplotlib中复制了您的示例。基本思想是将函数绘制为不可见的多边形,显示归一化的颜色图的图像(使用自定义范数函数将值包装在±pi/2
之外),然后将函数多边形作为剪切蒙版应用到该图像
代码:
# Function (improve smoothness of plot by increasing samples from 500)
x = np.linspace(-4,4,500)
y = abs(np.e**(2j*x - x**2/2))
# Set up figure
fig, ax = plt.subplots()
ax.set_ylim(ymin=0, ymax=1)
# Plot line without fill
line, = ax.fill(x, y, facecolor='none')
# Reshape x data for applying cmap
img_data = x.reshape(1, x.size)
# Set up norm between + and - pi/2
norm = mpl.colors.Normalize(vmin=-np.pi/2, vmax=np.pi/2)
# Use hsv cmap (cyclic rainbow)
cmap=plt.cm.hsv
# Function to apply norm cyclicly
def f(x):
return norm(x)%1
# Apply modified norm to img_data
cmap_data = f(img_data)
# Get limits
xmin, xmax = np.min(x), np.max(x)
ymin, ymax = np.min(y), np.max(y)
# Show cmap image
im = ax.imshow(cmap_data, aspect='auto', cmap=cmap, extent=[xmin,xmax,ymin,ymax])
# Clip image along line
im.set_clip_path(line)
输出: