我使用matplotlib来创建图。我必须用不同的颜色来标识每个图,这应该由Python自动生成。

你能不能给我一个方法,在同一个图里不同的图用不同的颜色?


当前回答

Matplotlib默认这样做。

例如:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

而且,正如你可能已经知道的,你可以很容易地添加一个图例:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

如果你想控制循环的颜色:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

如果您不熟悉matplotlib,本教程是一个很好的开始。

编辑:

首先,如果你有很多东西(>5),你想在一个图形上绘制,要么:

把它们放在不同的图上(考虑在一个图上使用几个子图),或者 使用颜色以外的东西(即标记样式或线条粗细)来区分它们。

否则,你将以一个非常混乱的情节结束!善待那些会读到你在做什么的人,不要试图把15种不同的东西塞进一个人的身上!!

除此之外,许多人在不同程度上都是色盲,区分众多微妙不同的颜色比你想象的要困难得多。

话虽如此,如果你真的想在一个轴上放20条线,用20种相对不同的颜色,这里有一种方法:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

其他回答

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from skspatial.objects import Line, Vector

for count in range(0,len(LineList),1):
        Line_Color = np.random.rand(3,)
        Line(StartPoint,EndPoint)).plot_3d(ax,c="Line"+str(count),label="Line"+str(count))


plt.legend(loc='lower left')
plt.show(block=True)     

上面的代码可以帮助你以随机的方式添加不同颜色的3D线条。你的彩色线条也可以通过标签="…"中提到的图例来引用。”参数。

老实说,我最喜欢的方法很简单:现在这对任意数量的地块都不适用,但它可以满足你到1163的需求。这是通过使用所有matplotlib的命名颜色的映射,然后随机选择它们。

from random import choice

import matplotlib.pyplot as plt
from matplotlib.colors import mcolors

# Get full named colour map from matplotlib
colours = mcolors._colors_full_map # This is a dictionary of all named colours
# Turn the dictionary into a list
color_lst = list(colours.values()) 

# Plot using these random colours
for n, plot in enumerate(plots):
    plt.scatter(plot[x], plot[y], color=choice(color_lst), label=n) 

不,它不能自动完成。是的,这是可能的。

import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))

一个图(图)中的每个图(轴)都有自己的颜色循环-如果你不强制每个图使用不同的颜色,所有的图都共享相同的颜色顺序,但是,如果我们稍微扩展一下“自动”的含义,这是可以做到的。


OP写道

[…我必须用不同的颜色来识别每个图,这应该由[Matplotlib]自动生成。

但是…Matplotlib自动为每条不同的曲线生成不同的颜色

In [10]: import numpy as np
    ...: import matplotlib.pyplot as plt

In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:

那么为什么是OP请求呢?如果我们继续读下去,我们就会成功

你能不能给我一个方法,在同一个图里不同的图用不同的颜色?

这是有道理的,因为每个图(Matplotlib中的每个轴)都有自己的color_cycle(更确切地说,在2018年,它的prop_cycle),并且每个图(轴)以相同的顺序重用相同的颜色。

In [12]: fig, axes = plt.subplots(2,3)

In [13]: for ax in axes.flatten():
    ...:     ax.plot((0,1), (0,1))

如果这是最初问题的意思,一种可能是明确地为每个图命名不同的颜色。

如果图是在循环中生成的(这经常发生),我们必须有一个额外的循环变量来覆盖Matplotlib自动选择的颜色。

In [14]: fig, axes = plt.subplots(2,3)

In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
    ...:     ax.plot((0,1), (0,1), short_color_name)

另一种可能是实例化一个cycler对象

from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()

fig, axes = plt.subplots(2,3)
for ax in axes.flat:
    ax.plot((0,1), (0,1), **next(actual_cycler))

注意,type(my_cycler)是cycler。循环器,但类型(actual_cycler)是itertools.cycle。

稍后再设置

如果你不知道你要绘制的图的数量,你可以改变颜色,一旦你绘制了它们,使用.lines直接从图中检索数字,我使用这个解决方案:

一些随机数据

import matplotlib.pyplot as plt
import numpy as np

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)


for i in range(1,15):
    ax1.plot(np.array([1,5])*i,label=i)

你需要的一段代码:

colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired   
colors = [colormap(i) for i in np.linspace(0, 1,len(ax1.lines))]
for i,j in enumerate(ax1.lines):
    j.set_color(colors[i])
  

ax1.legend(loc=2)

结果如下:

Matplot用不同的颜色给你的场景上色,但如果你想放特定的颜色

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()