如何为图中的每条绘制线选择新颜色

发布于 2024-10-17 03:58:03 字数 434 浏览 4 评论 0原文

我不想为每条绘制的线指定颜色,并且让每条线都有不同的颜色。但是如果我运行:

from matplotlib import pyplot as plt
for i in range(20):
    plt.plot([0, 1], [i, i])

plt.show()

那么我会得到以下输出:

上面代码输出的图形的图像

如果您查看上面的图像,您可以看到 matplotlib 尝试为每条不同的线选择颜色,但最终它重复使用颜色 - 前十行使用与后十行相同的颜色。我只是想阻止它重复已使用的颜色和/或为其提供要使用的颜色列表。

I'd like to NOT specify a color for each plotted line, and have each line get a distinct color. But if I run:

from matplotlib import pyplot as plt
for i in range(20):
    plt.plot([0, 1], [i, i])

plt.show()

then I get this output:

Image of the graph output by the code above

If you look at the image above, you can see that matplotlib attempts to pick colors for each line that are different, but eventually it re-uses colors - the top ten lines use the same colors as the bottom ten. I just want to stop it from repeating already used colors AND/OR feed it a list of colors to use.

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

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

发布评论

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

评论(8

甜心 2024-10-24 03:58:03

我通常使用其中的第二个:

from matplotlib.pyplot import cm
import numpy as np

#variable n below should be number of curves to plot

#version 1:

color = cm.rainbow(np.linspace(0, 1, n))
for i, c in enumerate(color):
   plt.plot(x, y, c=c)

#or version 2:

color = iter(cm.rainbow(np.linspace(0, 1, n)))
for i in range(n):
   c = next(color)
   plt.plot(x, y, c=c)

示例 2:
带有 iter 的示例图,下一个颜色

I usually use the second one of these:

from matplotlib.pyplot import cm
import numpy as np

#variable n below should be number of curves to plot

#version 1:

color = cm.rainbow(np.linspace(0, 1, n))
for i, c in enumerate(color):
   plt.plot(x, y, c=c)

#or version 2:

color = iter(cm.rainbow(np.linspace(0, 1, n)))
for i in range(n):
   c = next(color)
   plt.plot(x, y, c=c)

Example of 2:
example plot with iter,next color

谎言月老 2024-10-24 03:58:03

matplotlib 1.5+

您可以使用axes.set_prop_cycle(示例)。

matplotlib 1.0-1.4

您可以使用axes.set_color_cycle(示例)。

matplotlib 0.x

您可以使用Axes.set_default_color_cycle。

matplotlib 1.5+

You can use axes.set_prop_cycle (example).

matplotlib 1.0-1.4

You can use axes.set_color_cycle (example).

matplotlib 0.x

You can use Axes.set_default_color_cycle.

北城半夏 2024-10-24 03:58:03

您可以使用预定义的“定性颜色图”,如下所示:

import matplotlib as mpl
name = "Accent"
cmap = mpl.colormaps[name]  # type: matplotlib.colors.ListedColormap
colors = cmap.colors  # type: list
axes.set_prop_cycle(color=colors)

matplotlib 3.5(从 2021 年起)及更高版本支持 matplotlib.colormaps[],而较旧的 matplotlib.cm.get_cmap()< /code> API 已弃用,并将在 matplotlib 3.9 (2024) 中删除。请参阅 https://github.com/matplotlib/matplotlib/issues/10840 进行讨论为什么你不能调用axes.set_prop_cycle(color=cmap)。

预定义的定性颜色图列表可在 https://matplotlib.org/gallery/color/colormap_reference 中找到。 html :

定性颜色图列表

You can use a predefined "qualitative colormap" like this:

import matplotlib as mpl
name = "Accent"
cmap = mpl.colormaps[name]  # type: matplotlib.colors.ListedColormap
colors = cmap.colors  # type: list
axes.set_prop_cycle(color=colors)

matplotlib.colormaps[] is supported on matplotlib 3.5 (from 2021) and above, while the older matplotlib.cm.get_cmap() API is deprecated and will be removed in matplotlib 3.9 (2024). See https://github.com/matplotlib/matplotlib/issues/10840 for discussion on why you can't call axes.set_prop_cycle(color=cmap).

A list of predefined qualititative colormaps is available at https://matplotlib.org/gallery/color/colormap_reference.html :

List of qualitative colormaps

铃予 2024-10-24 03:58:03

prop_cycle

color_cycle 在 1.5 中已被弃用,以支持这种概括:http://matplotlib.org/users/whats_new.html#added-axes-prop-cycle-key-to-rcparams

# cycler is a separate package extracted from matplotlib.
from cycler import cycler
import matplotlib.pyplot as plt

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b'])))
plt.plot([1, 2])
plt.plot([2, 3])
plt.plot([3, 4])
plt.plot([4, 5])
plt.plot([5, 6])
plt.show()

还显示在(现在命名不当)示例中: http://matplotlib.org/1.5.1/examples/color/color_cycle_demo.html 提到:https://stackoverflow.com/a/4971431/895245

在 matplotlib 1.5.1 中测试。

prop_cycle

color_cycle was deprecated in 1.5 in favor of this generalization: http://matplotlib.org/users/whats_new.html#added-axes-prop-cycle-key-to-rcparams

# cycler is a separate package extracted from matplotlib.
from cycler import cycler
import matplotlib.pyplot as plt

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b'])))
plt.plot([1, 2])
plt.plot([2, 3])
plt.plot([3, 4])
plt.plot([4, 5])
plt.plot([5, 6])
plt.show()

Also shown in the (now badly named) example: http://matplotlib.org/1.5.1/examples/color/color_cycle_demo.html mentioned at: https://stackoverflow.com/a/4971431/895245

Tested in matplotlib 1.5.1.

以为你会在 2024-10-24 03:58:03

我不知道你是否可以自动更改颜色,但你可以利用你的循环来生成不同的颜色:

for i in range(20):
   ax1.plot(x, y, color = (0, i / 20.0, 0, 1)

在这种情况下,颜色将从黑色到 100% 绿色,但如果你愿意,你可以调整它。

请参阅 matplotlibplot() 文档 并查找 color 关键字参数。

如果您想提供颜色列表,只需确保您有一个足够大的列表,然后使用循环的索引来选择颜色

colors = ['r', 'b', ...., 'w']

for i in range(20):
   ax1.plot(x, y, color = colors[i])

I don't know if you can automatically change the color, but you could exploit your loop to generate different colors:

for i in range(20):
   ax1.plot(x, y, color = (0, i / 20.0, 0, 1)

In this case, colors will vary from black to 100% green, but you can tune it if you want.

See the matplotlib plot() docs and look for the color keyword argument.

If you want to feed a list of colors, just make sure that you have a list big enough and then use the index of the loop to select the color

colors = ['r', 'b', ...., 'w']

for i in range(20):
   ax1.plot(x, y, color = colors[i])
以可爱出名 2024-10-24 03:58:03

正如 Ciro 的回答指出,您可以使用 prop_cycle 设置 matplotlib 循环的颜色列表通过。但有多少种颜色呢?如果您想对具有不同行数的大量绘图使用相同的颜色循环该怎么办?

一种策略是使用类似于 https://gamedev.stackexchange.com/a/46469/22397< 中的公式/a>,生成无限的颜色序列,其中每种颜色都试图与其之前的所有颜色显着不同。

不幸的是,prop_cycle 不会接受无限序列 - 如果你传递一个序列,它将永远挂起。但我们可以采用从这样的序列生成的前 1000 种颜色,并将其设置为颜色循环。这样,对于具有任何合理行数的绘图,您应该获得可区分的颜色。

示例:

from matplotlib import pyplot as plt
from matplotlib.colors import hsv_to_rgb
from cycler import cycler

# 1000 distinct colors:
colors = [hsv_to_rgb([(i * 0.618033988749895) % 1.0, 1, 1])
          for i in range(1000)]
plt.rc('axes', prop_cycle=(cycler('color', colors)))

for i in range(20):
    plt.plot([1, 0], [i, i])

plt.show()

输出:

上面代码的图形输出

现在,所有颜色都不同了 - 尽管我承认我很难区分其中的一些颜色!

As Ciro's answer notes, you can use prop_cycle to set a list of colors for matplotlib to cycle through. But how many colors? What if you want to use the same color cycle for lots of plots, with different numbers of lines?

One tactic would be to use a formula like the one from https://gamedev.stackexchange.com/a/46469/22397, to generate an infinite sequence of colors where each color tries to be significantly different from all those that preceded it.

Unfortunately, prop_cycle won't accept infinite sequences - it will hang forever if you pass it one. But we can take, say, the first 1000 colors generated from such a sequence, and set it as the color cycle. That way, for plots with any sane number of lines, you should get distinguishable colors.

Example:

from matplotlib import pyplot as plt
from matplotlib.colors import hsv_to_rgb
from cycler import cycler

# 1000 distinct colors:
colors = [hsv_to_rgb([(i * 0.618033988749895) % 1.0, 1, 1])
          for i in range(1000)]
plt.rc('axes', prop_cycle=(cycler('color', colors)))

for i in range(20):
    plt.plot([1, 0], [i, i])

plt.show()

Output:

Graph output by the code above

Now, all the colors are different - although I admit that I struggle to distinguish a few of them!

誰ツ都不明白 2024-10-24 03:58:03

您还可以更改 matplotlibrc 文件中的默认颜色循环。
如果您不知道该文件在哪里,请在 python 中执行以下操作:

import matplotlib
matplotlib.matplotlib_fname()

这将显示当前使用的 matplotlibrc 文件的路径。
在该文件中,您会在许多其他设置中找到axes.color.cycle 的设置。只需输入您想要的颜色序列,您就会在您制作的每个图中找到它。
请注意,您还可以在 matplotlib 中使用所有有效的 html 颜色名称。

You can also change the default color cycle in your matplotlibrc file.
If you don't know where that file is, do the following in python:

import matplotlib
matplotlib.matplotlib_fname()

This will show you the path to your currently used matplotlibrc file.
In that file you will find amongst many other settings also the one for axes.color.cycle. Just put in your desired sequence of colors and you will find it in every plot you make.
Note that you can also use all valid html color names in matplotlib.

叹倦 2024-10-24 03:58:03
  • matplotlib.cm.get_cmapmatplotlib.pyplot.cm.get_cmap 已弃用,如 matplotlib 3.7.0:弃用顶级 cmap mpl.cm 中的注册和访问函数
  • 请改用 matplotlib.colormaps[name]matplotlib.colormaps.get_cmap(obj)
  • .get_cmap 不再具有 lut 参数。相反,使用 .resampled
  • cmap = mpl.colormaps.get_cmap('viridis').resampled(20) 创建一个 matplotlib.colors.ListedColormap目的。
    • 另外cmap = mpl.colormaps['viridis'].resampled(20)
  • colors = mpl.colormaps.get_cmap('viridis').resampled(20).colors 创建颜色数字的数组。
import matplotlib as mpl
import matplotlib.pyplot as mpl
import numpy as np

colors = mpl.colormaps.get_cmap('viridis').resampled(20).colors

for i, color in enumerate(colors):
    plt.plot([0, 1], [i, i], color=color)

plt.show()

输入图片这里的描述


cmap = mpl.colormaps.get_cmap('summer').resampled(20)
colors = cmap(np.arange(0, cmap.N)) 

for i, color in enumerate(colors):
    plt.plot([0, 1], [i, i], color=color)

plt.show()

在此处输入图像描述

  • matplotlib.cm.get_cmap and matplotlib.pyplot.cm.get_cmap are deprecated, as noted in matplotlib 3.7.0: Deprecation of top-level cmap registration and access functions in mpl.cm
  • Use matplotlib.colormaps[name] or matplotlib.colormaps.get_cmap(obj) instead.
  • .get_cmap no longer has the lut parameter. Instead, use .resampled
  • cmap = mpl.colormaps.get_cmap('viridis').resampled(20) creates a matplotlib.colors.ListedColormap object.
    • Also cmap = mpl.colormaps['viridis'].resampled(20)
  • colors = mpl.colormaps.get_cmap('viridis').resampled(20).colors create an array of color numbers.
import matplotlib as mpl
import matplotlib.pyplot as mpl
import numpy as np

colors = mpl.colormaps.get_cmap('viridis').resampled(20).colors

for i, color in enumerate(colors):
    plt.plot([0, 1], [i, i], color=color)

plt.show()

enter image description here


cmap = mpl.colormaps.get_cmap('summer').resampled(20)
colors = cmap(np.arange(0, cmap.N)) 

for i, color in enumerate(colors):
    plt.plot([0, 1], [i, i], color=color)

plt.show()

enter image description here

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