具有色标和一种颜色的色图(不需要的值)

时间:2019-05-28 16:47:08

标签: python-3.x matplotlib

我想在3D中绘制一个由3个变量(相同的最小值,相同的最大值,相同的间距)组成的网格,并且我希望网格上的每个点根据函数f来具有特定的颜色,f是这些函数的函数3个变量,但当函数的值优于我为其分配另一种颜色的特定阈值时。

以下是到目前为止我尝试过的代码:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.colors
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import math
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

%matplotlib notebook

x = np.arange(0.001, 0.175, 0.01)
y = np.arange(0.001, 0.175, 0.01)
z = np.arange(0.001, 0.175, 0.01)

X, Y, Z = np.meshgrid(x, y, z)

def function(X,Y,Z):
   '''function of (X,Y,Z) going from 0 to high values'''
   return(f)

f=function(X,Y,Z)

#flatten the f array (I think there is a function to flatten an array but I have seen it to late)
fflat=[]
for l in f:
    for p in l:
        for t in p:
            fflat.append(t) 

#masking high values with the highest interesting value: maxV              
mfflat = ma.masked_greater(fflat, maxV)
mfflat = mfflat.filled(maxV)

#normalizing values and mapping to veridis cmap:
cmap = matplotlib.cm.get_cmap('viridis')
norm = matplotlib.colors.Normalize(vmin=min(mfflat), vmax=maxV) #(vmax=maxV=max(mfflat))
colors = [cmap(norm(value)) for value in mfflat]

#plot
ax.scatter(X, Y, Z, color=colors, s=10, alpha=1)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)

问题在于,现在所有“多余的高值”(即> maxV的值)与我的“最大期望值”(即maxV…)具有相同的颜色。

我希望在Veridis色标之外的所有“不需要的值”,并为它们提供另一种独特的颜色。

感谢您的帮助! 干杯

1 个答案:

答案 0 :(得分:0)

感谢ImportanceOfBeingErnest的答案(有时我应该更仔细地阅读文档...),我只需要使用: cmap.set_over ,下面是正确的代码:

x = np.arange(0.001, 0.175, 0.01)
y = np.arange(0.001, 0.175, 0.01)
z = np.arange(0.001, 0.175, 0.01)

X, Y, Z = np.meshgrid(x, y, z)

def function(X,Y,Z):
   '''function of (X,Y,Z) going from 0 to high values'''
   return(f)

f=function(X,Y,Z)

#flatten the f array (I think there is a function to flatten an array but I have seen it to late)
fflat=[]
for l in f:
    for p in l:
        for t in p:
            fflat.append(t) 

cmap = plt.cm.get_cmap('viridis')
cmap.set_over(color=(0,0,0), alpha=0.5)
norm = matplotlib.colors.Normalize(vmin=minV, vmax=maxV)
colors = [cmap(norm(value)) for value in fflat]

#plot
ax.scatter(X, Y, Z, color=colors, s=10, alpha=1)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)

与此同时,我通过有选择地创建“颜色”列表找到了解决方法,这当然不如使用cmap.set_over干净:

colors=[]
for value in fflat:
    if minV <= value <= maxV:
        colors.append(cmap(norm(value)))
    else:
        colors.append((255/258,255/258,255/258,0))