我正在使用 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,the tutorial is a good place to start .
编辑:
首先,如果您想在一个图形上绘制很多 (>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()
https://stackoverflow.com/questions/4805048/