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

新手上路,请多包涵

我正在使用 matplotlib 创建绘图。我必须用 Python 自动生成的不同颜色来识别每个图。

你能给我一个方法来为同一个图中的不同地块放置不同的颜色吗?

原文由 pottigopi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 353
1 个回答

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

基于给定颜色图的 20 行的独特颜色

原文由 Joe Kington 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题