如何使用 Matplotlib 绘制类似于以下图像的图形?
这些图像的作用是结合两个可视化图。第一个(背景)是一个简单的图,可以使用 imshow、pcolor、pcolormesh 来绘制,而另一个使用网格纹理,其中模糊(w 因子)决定了一些特征,在这种情况下,是不确定性。我不知道如何做的是绘制不同模糊度的不同线条。对于每个像素,我都有一个不确定性,我应该在这像素中绘制一条线,不确定性表示为线条模糊。
我我不知道如何用 Matplotlib 来绘制这些具有模糊的线条。
任何帮助都将不胜感激。 提前谢谢。
解决方案
以下是如何使用 Matplotlib 绘制具有不同模糊度线条的解决方案:
- 使用
smooth2d函数对图像进行平滑处理。此函数使用汉宁窗口对图像进行平滑,并返回平滑后的图像。 - 将
GaussianFilter类应用于平滑后的图像。此类使用高斯滤波器对图像进行模糊处理,并返回模糊后的图像。 - 将模糊后的图像绘制到轴上。
下面的代码演示了如何使用 smooth2d 函数和 GaussianFilter 类来绘制具有不同模糊度的线条:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from noise import snoise2
def smooth2d(A, sigma=3):
window_len = max(int(sigma), 3)*2+1
A1 = np.array([smooth1d(x, window_len) for x in np.asarray(A)])
A2 = np.transpose(A1)
A3 = np.array([smooth1d(x, window_len) for x in A2])
A4 = np.transpose(A3)
return A4
class GaussianFilter(object):
"simple gauss filter"
def __init__(self, sigma, alpha=0.5, color=None):
self.sigma = sigma
self.alpha = alpha
if color is None:
self.color=(0, 0, 0)
else:
self.color=color
def process_image(self, padded_src, dpi):
tgt_image = np.zeros_like(padded_src)
aa = smooth2d(padded_src[:,:,-1]*self.alpha,
self.sigma/72.*dpi)
tgt_image[:,:,-1] = aa
tgt_image[:,:,:-1] = self.color
return tgt_image
#Create the landscape
octaves = 4
freq = octaves * 100
xs, ys = np.linspace(0.0, 100.0, 100), np.linspace(0.0, 100.0, 100)
X,Y = np.meshgrid(xs,ys)
Z1 = np.zeros(X.shape)
for i,x in enumerate(xs):
for j,y in enumerate(ys):
Z1[i][j] = int(snoise2(x/freq, y/freq, octaves) * 127.0 + 128.0)
# get some different colours for the surface.
faceValues = np.zeros(X.shape)
noise = []
for i,x in enumerate(xs):
for j,y in enumerate(ys):
faceValues[i][j] = snoise2(4*x/freq, 4*y/freq, octaves)
jet = cm.get_cmap("jet")
faceColours = []
for i,x in enumerate(xs):
faceColours.append([])
for j,y in enumerate(ys):
normalised = (faceValues[i][j] - faceValues.min()) / (faceValues.max() - faceValues.min())
faceColours[i].append(jet(normalised))
faceValues[i][j] = normalised
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X,Y,Z1, cmap=cm.jet, linewidth=0.2, cstride=2, rstride=2, facecolors=faceColours, vmin=0, vmax=1)
#This decides where we draw the rectangle to be inspecting.
rect = ((25,45),(65,70))
gaussFilter = GaussianFilter(3)
ax.grid(linestyle="-", linewidth=2, agg_filter=gaussFilter)
运行此代码将生成以下图像:
[图片]
此图像显示了具有不同模糊度的线条。模糊度由高斯滤波器的 sigma 参数控制。