Matplotlib 通过颜色图绘制带有颜色的线条 [英] Matplotlib Plot Lines with Colors Through Colormap
问题描述
我正在一个图上绘制多条线,我希望它们在颜色图的范围内运行,而不仅仅是相同的 6 或 7 种颜色.代码类似于:
I am plotting multiple lines on a single plot and I want them to run through the spectrum of a colormap, not just the same 6 or 7 colors. The code is akin to this:
for i in range(20):
for k in range(100):
y[k] = i*x[i]
plt.plot(x,y)
plt.show()
无论是颜色图jet"还是我从 seaborn 导入的另一个颜色图,我都得到了以相同顺序重复的相同 7 种颜色.我希望能够绘制多达约 60 条不同的线条,所有线条都具有不同的颜色.
Both with colormap "jet" and another that I imported from seaborn, I get the same 7 colors repeated in the same order. I would like to be able to plot up to ~60 different lines, all with different colors.
推荐答案
Matplotlib 颜色图接受一个参数(0..1
、标量或数组),您可以使用该参数从颜色图中获取颜色.例如:
The Matplotlib colormaps accept an argument (0..1
, scalar or array) which you use to get colors from a colormap. For example:
col = pl.cm.jet([0.25,0.75])
为您提供一个具有(两种)RGBA 颜色的数组:
Gives you an array with (two) RGBA colors:
array([[ 0. , 0.50392157, 1. , 1. ],[ 1. , 0.58169935, 0. , 1. ]])
array([[ 0. , 0.50392157, 1. , 1. ], [ 1. , 0.58169935, 0. , 1. ]])
您可以使用它来创建 N
种不同的颜色:
You can use that to create N
different colors:
import numpy as np
import matplotlib.pylab as pl
x = np.linspace(0, 2*np.pi, 64)
y = np.cos(x)
pl.figure()
pl.plot(x,y)
n = 20
colors = pl.cm.jet(np.linspace(0,1,n))
for i in range(n):
pl.plot(x, i*y, color=colors[i])
这篇关于Matplotlib 通过颜色图绘制带有颜色的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!