在matplotlib中绘制不同的颜色 [英] plotting different colors in matplotlib

查看:105
本文介绍了在matplotlib中绘制不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

How do I automatically change colors in the for loop?

推荐答案

@tcaswell已经回答了,但是我正在输入答案,因此我将继续进行发布...

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

您可以通过多种不同的方式来执行此操作.首先,matplotlib将自动在颜色之间循环.默认情况下,它会循环显示蓝色,绿色,红色,青色,洋红色,黄色和黑色:

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

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()

如果要控制matplotlib循环显示哪些颜色,请使用ax.set_color_cycle:

If you want to control which colors matplotlib cycles through, use 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()

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

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

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()

最后,如果您想自动从现有颜色图:

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()

这篇关于在matplotlib中绘制不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆