在matplotlib中使用Colormaps设置线条的颜色

bvuwiixz  于 2023-05-01  发布在  其他
关注(0)|答案(5)|浏览(273)

如何在matplotlib中设置一条线的颜色,它在运行时提供了标量值(比如说jet)?我尝试了几种不同的方法,我想我被难住了。values[]是一个标量数组。曲线是一组一维数组,标签是一组文本字符串。每个数组具有相同的长度。

fig = plt.figure()
ax = fig.add_subplot(111)
jet = colors.Colormap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    retLine, = ax.plot(line, color=colorVal)
    #retLine.set_color()
    lines.append(retLine)
ax.legend(lines, labels, loc='upper right')
ax.grid()
plt.show()
5fjcxozz

5fjcxozz1#

您收到的错误是由于您如何定义jet。您正在创建名为'jet'的基类Colormap,但这与获取'jet'色彩Map表的默认定义有很大不同。不应直接创建此基类,而应仅示例化子类。
您在示例中发现的是Matplotlib中的错误行为。运行此代码时,应该会生成更清晰的错误消息。
这是您的示例的更新版本:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)

fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line 
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()

lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    colorText = (
        'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
        )
    retLine, = ax.plot(line,
                       color=colorVal,
                       label=colorText)
    lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()

导致:

使用ScalarMappable比我的相关答案中提出的方法有所改进:使用matplotlib创建超过20种独特的图例颜色

czq61nw1

czq61nw12#

我认为包含一个我认为更简单的方法是有益的,它使用numpy的linspace和matplotlib的cm-type对象。上面的解决方案有可能是针对旧版本。我用的是Python 3。4.3,matplotlib 1.4.3和numpy 1。9.3.,我的解决方案如下。

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()

这导致跨越整个cm的1000条独特颜色的线。如下图所示。如果运行这个脚本,您会发现可以放大各个行。

现在,假设我希望我的1000行颜色只是跨越400到600行之间的绿色部分。我只是简单地将开始和停止值更改为0。4和0.6,这导致仅使用cm的20%。喷射颜色图0之间。4和0.6。

因此,在一行摘要中,您可以从www. example创建rgba颜色列表 www.example.com colormap相应地:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

在本例中,我使用了通常调用的map jet,但您可以通过调用以下命令来找到matplotlib版本中可用的颜色Map的完整列表:

>>> from matplotlib import cm
>>> dir(cm)
pftdvrlh

pftdvrlh3#

matplotlib中的线条样式、标记和定性颜色的组合:

import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors   # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
    plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);

更新:不仅支持ListedColormap,还支持LinearSegmentedColormap

import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
    ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})

ttvkxqim

ttvkxqim4#

你可以做我写的从我删除的帐户(禁止新职位:(有)。它相当简单和好看。
我通常使用这3个中的第3个,我也是检查1和2版本。

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

示例3:
Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

u0sqgete

u0sqgete5#

您可以使用Seaborn:

palette = sns.color_palette("hls", number_of_colors)

https://seaborn.pydata.org/tutorial/color_palettes.html#using-circular-color-systems

相关问题