对 matplotlib 线图使用颜色图

npr*_*oss 7 python plot matplotlib colormap

我想使用反向 Spectral colormap

https://matplotlib.org/examples/color/colormaps_reference.html

对于线图。

这适用于十六进制图:

color_map = plt.cm.Spectral_r
image = plt.hexbin(x,y,cmap=color_map)
Run Code Online (Sandbox Code Playgroud)

但是当我这样做的时候

ax1.plot(x,y, cmp=color_map)
Run Code Online (Sandbox Code Playgroud)

这给了我::

AttributeError: 未知属性 cmap

请注意,我只想设置colormap并让matplotliob其余的工作;即我不想color=' argument在 .plot 命令中有一个。

Joe*_*ntz 8

您可以在此处查看最佳答案 - 第三个变体是您想要的:

使用 matplotlib 颜色图进行颜色循环

您需要提前知道要绘制多少条线,否则它不知道如何从范围中选择颜色。


ast*_*iko 6

我认为seaborn的color_palette功能对于这个目的来说非常方便。它可以在with语句中用于临时设置一个图或一组图的颜色循环。例如:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

with sns.color_palette("Spectral", n_colors=10):
    plt.plot(np.random.rand(5, 10))
Run Code Online (Sandbox Code Playgroud)

您可以与任何预定义的matplotlibseaborn colormap一起使用,或提供自定义颜色序列。