matplotlib 使用contourf()自定义等高线图

q5lcpyga  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(149)

我使用matplotlib绘制一个函数的轮廓。我想以这样的方式绘制,直到函数的某个值显示相同的颜色(说,黑色)和超过该函数的颜色梯度值显示。我是新的轮廓绘图,我不知道如何实现这一点。这里是一个代码示例。这段代码的结果到连续变化的颜色。我想要一个固定的颜色高达threshold和超过该值的颜色应该以连续的方式变化。

x = np.linspace(0,50, 1000)
y = np.linspace(0, 20, 1000)
[X,Y] = np.meshgrid(x,y)

Z = np.sin(X) + np.cos(Y)
threshold = 1.03
lvls = np.linspace((Z).min(),(Z).max(),3000)
contour_plot=plt.contourf(X,Y,Z,levels=lvls,cmap='viridis')
colorbar = plt.colorbar(contour_plot)

字符串

ewm0tg9j

ewm0tg9j1#

请参阅下面我的解决方案,基于matplotlib文档中的示例。

import numpy as np

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

# Define data
x = np.linspace(0,50, 100)
y = np.linspace(0, 20, 100)
[X,Y] = np.meshgrid(x,y)

Z = np.sin(X) + np.cos(Y)
threshold = 1.03

# Get the colormap and the colors inside it
viridis = matplotlib.colormaps.get_cmap('viridis')
n_of_colors = 500 # with this you can control the "sampling frequency" of the original colormap
newcolors = viridis(np.linspace(0, 
                                1, 
                                n_of_colors 
                    )) 
black = np.array([0.0, 0.0, 0.0, 1])

# Get the index corresponding to the threshold value
threshold_idx = int(((threshold - Z.min()) / (Z.max() - Z.min())) * n_of_colors)
# Set all the colors below the threshold (index) to black
newcolors[:threshold_idx, :] = black
# Create a new colormaps with the colors you just defined
newcmp = ListedColormap(newcolors)

# Plot
lvls = np.linspace((Z).min(),(Z).max(),3000)
contour_plot = plt.contourf(X,Y,Z,levels=lvls,cmap=newcmp)
colorbar = plt.colorbar(contour_plot)

plt.show()

字符串
生成以下图像x1c 0d1x

**旁注。**您在MWE中给出的网格非常重,需要处理,必须缩小规模。

希望这对你有帮助!

相关问题