如何在单个图中为不同的图获得不同颜色的线条

发布于 2024-10-14 12:29:43 字数 102 浏览 1 评论 0原文

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

您能给我一种在同一图中为不同的图添加不同颜色的方法吗?

I am using matplotlib to create the plots. I have to identify each plot with a different color which should be automatically generated by Python.

Can you please give me a method to put different colors for different plots in the same figure?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

蹲在坟头点根烟 2024-10-21 12:29:43

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)个东西,可以:

  1. 将它们放在不同的图上(考虑在一个图上使用一些子图),或者
  2. 使用颜色以外的其他内容(即标记样式或线条粗细)来区分它们。

否则,你将会得到一个非常混乱的情节!善待那些将要阅读你正在做的事情的人,不要试图将 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()

“基于给定颜色图的

Matplotlib does this by default.

E.g.:

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

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

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

Basic plot with legend

If you want to control the colors that will be cycled through:

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

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

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

Unique colors for 20 lines based on a given colormap

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

Unique colors for 20 lines based on a given colormap

杀お生予夺 2024-10-21 12:29:43

稍后设置它们

如果您不知道要绘制的图的数量,则可以在绘制它们后更改颜色,使用 .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)

结果如下:在此处输入图像描述

Setting them later

If you don't know the number of the plots you are going to plot you can change the colours once you have plotted them retrieving the number directly from the plot using .lines, I use this solution:

Some random data

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)

The piece of code that you need:

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)

The result is the following:enter image description here

满栀 2024-10-21 12:29:43

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

import matplotlib.pyplot as plt
#                                    _____ VV______
my_colors = plt.rcParams['axes.prop_cycle']() 
# note that we CALLED 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.Cycler 但 <代码>类型(actual_cycler)是<代码>itertools.cycle。

TL;DR No, it can't be done automatically. Yes, it is possible.

import matplotlib.pyplot as plt
#                                    _____ VV______
my_colors = plt.rcParams['axes.prop_cycle']() 
# note that we CALLED the prop_cycle ‾‾‾‾‾‾ΛΛ‾‾‾‾‾‾

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

enter image description here


The OP wrote

[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].

But... Matplotlib automatically generates different colors for each different curve

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]:

enter image description here

So why the OP request? If we continue to read, we have

Can you please give me a method to put different colors for different plots in the same figure?

and it make sense, because each plot (each axes in Matplotlib's parlance) has its own color_cycle (or rather, in 2018, its prop_cycle) and each plot (axes) reuses the same colors in the same order.

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

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

enter image description here

If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.

If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by 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)

enter image description here

Another possibility is to instantiate a cycler object

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

enter image description here

Note that type(my_cycler) is cycler.Cycler but type(actual_cycler) is itertools.cycle.

海螺姑娘 2024-10-21 12:29:43

我想对上一篇文章中给出的最后一个循环答案进行一个小小的改进(该文章是正确的,仍然应该被接受)。标记最后一个示例时所做的隐含假设是 plt.label(LIST) 将标签编号 X 放入 LIST 中,其中的行对应于第 X 次 plot< /code> 被调用。我以前也遇到过这种方法的问题。根据 matplotlibs 文档构建图例并自定义其标签的推荐方法( http://matplotlib.org/users/legend_guide.html# adjustment-the-order-of-legend-item) 是为了有一种温暖的感觉,标签与您认为的确切情节一致做:

...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
    x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
    plotHandles.append(x)
    labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)

**: Matplotlib 图例不工作

I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST) puts label number X in LIST with the line corresponding to the Xth time plot was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:

...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
    x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
    plotHandles.append(x)
    labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)

**: Matplotlib Legends not working

风吹雨成花 2024-10-21 12:29:43

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

Matplot colors your plot with different colors , but incase you wanna put specific colors

    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()
吾家有女初长成 2024-10-21 12:29:43
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 线条。您的彩色线条也可以通过 label="... " 参数中提到的图例的帮助来引用。

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)     

The above code might help you to add 3D lines with different colours in a randomized fashion. Your colored lines can also be referenced with a help of a legend as mentioned in the label="... " parameter.

你对谁都笑 2024-10-21 12:29:43

老实说,我最喜欢的方法非常简单:现在这不适用于任意大量的绘图,但它最多可以处理 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) 

Honestly, my favourite way to do this is pretty simple: Now this won't work for an arbitrarily large number of plots, but it will do you up to 1163. This is by using the map of all matplotlib's named colours and then selecting them at random.

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) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文