Python 在 matplotlib 中绘制不同的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16006572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:34:42  来源:igfitidea点击:

plotting different colors in matplotlib

pythonmatplotlib

提问by lord12

Suppose I have a for loop and I want to plot points in different colors:

假设我有一个 for 循环,我想用不同的颜色绘制点:

for i in range(5):
 plt.plot(x,y,col=i)

How do I automatically change colors in the for loop?

如何在 for 循环中自动更改颜色?

回答by tacaswell

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

回答by Joe Kington

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

@tcaswell 已经回答了,但我正在输入我的答案,所以我会继续发布......

There are a number of different ways you could do this. To begin with, matplotlibwill automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

有许多不同的方法可以做到这一点。首先,matplotlib将自动循环显示颜色。默认情况下,它会在蓝色、绿色、红色、青色、洋红色、黄色、黑色之间循环:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

在此处输入图片说明

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

如果要控制 matplotlib 循环的颜色,请使用ax.set_color_cycle

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

在此处输入图片说明

If you'd like to explicitly specify the colors that will be used, just pass it to the colorkwarg (html colors names are accepted, as are rgb tuples and hex strings):

如果您想明确指定将使用的颜色,只需将其传递给colorkwarg(接受 html 颜色名称,如 rgb 元组和十六进制字符串):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

在此处输入图片说明

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

最后,如果您想从现有颜色图中自动选择指定数量的颜色:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

在此处输入图片说明

回答by gboffi

Joe Kington's excellent answeris already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cyclermodule) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

Joe Kington优秀回答已经有 4 年的历史了,Matplotlib 已经逐渐改变(特别是cycler模块的引入),新的主要版本 Matplotlib 2.0.x 引入了从角度来看很重要的风格差异默认使用的颜色。

The color of individual lines

单条线的颜色

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the colorkeyword argument,

单个线条的颜色(以及不同绘图元素的颜色,例如散点图中的标记)由color关键字参数控制,

plt.plot(x, y, color=my_color)

my_coloris either

my_color或者是

The color cycle

颜色周期

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

默认情况下,不同的线条使用不同的颜色绘制,默认情况下定义并以循环方式使用(因此命名为 color cycle)。

The color cycle is a property of the axesobject, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

颜色循环是axes对象的一个属性,在旧版本中只是一系列有效的颜色名称(默认情况下是一个由一个字符颜色名称组成的字符串"bgrcmyk"),您可以将其设置为

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a commentthis API has been deprecated, more on this later).

(如评论中所述,此 API 已被弃用,稍后会详细介绍)。

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

在Matplotlib 2.0的默认颜色周期["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"],所述维加category10调色板

enter image description here

在此处输入图片说明

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

(图片是来自https://vega.github.io/vega/docs/schemes/的截图)

The cyclermodule: composable cycles

所述循环仪模块:组合的周期

The following code shows that the color cycle notion has been deprecated

以下代码显示颜色循环概念已被弃用

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

现在相关的属性是 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cyclewas a generic sequence of valid color denominations, now by default it is a cyclerobject containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

以前,这color_cycle是一个有效颜色面额的通用序列,现在默认情况下它是一个cycler包含标签 ( 'color') 和有效颜色面额序列的对象。相对于之前的界面向前迈出的一步是,不仅可以在线条颜色上循环,还可以在其他线条属性上循环,例如,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cyclerobjects are composableand when you iterate on a composed cyclerwhat you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

如您所见,cycler对象是可组合的,当您对组合进行迭代时cycler,每次迭代都会得到一个包含plt.plot.

You can use the new defaults on a per axesobject ratio,

您可以对每个axes对象的比率使用新的默认值,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

或者您可以临时安装新的默认值

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrcfile.

或完全更改默认编辑.matplotlibrc文件。

Last possibility, use a context manager

最后一种可能性,使用上下文管理器

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cyclerused in a group of different plots, reverting to defaults at the end of the context.

cycler在一组不同的图中使用新的,在上下文结束时恢复为默认值。

The doc string of the cycler()function is useful, but the (not so much) gory details about the cyclermodule and the cycler()function, as well as examples, can be found in the fine docs.

cycler()函数的文档字符串很有用,但是关于cycler模块和cycler()函数的(不是那么多)血腥的细节,以及示例,可以在 Fine docs 中找到。