在matplotlib上的散点图中为每个系列设置不同的颜色 [英] Setting different color for each series in scatter plot on matplotlib
问题描述
假设我有三个数据集:
X = [1,2,3,4]
Y1 = [4,8,12,16]
Y2 = [1,4,9,16]
我可以散布此图:
from matplotlib import pyplot as plt
plt.scatter(X,Y1,color='red')
plt.scatter(X,Y2,color='blue')
plt.show()
我该如何用10套来做到这一点?
How can I do this with 10 sets?
我进行了搜索,可以找到我所问的内容的任何参考.
I searched for this and could find any reference to what I'm asking.
(希望)澄清我的问题
如果我多次调用散点图,则只能在每个散点图上设置相同的颜色.另外,我知道我可以手动设置颜色阵列,但是我敢肯定有更好的方法可以做到这一点. 然后我的问题是:如何自动散布我的多个数据集,每个数据集具有不同的颜色.
If I call scatter multiple times, I can only set the same color on each scatter. Also, I know I can set a color array manually but I'm sure there is a better way to do this. My question is then, "How can I automatically scatter-plot my several data sets, each with a different color.
如果有帮助,我可以轻松地为每个数据集分配一个唯一的编号.
If that helps, I can easily assign a unique number to each data set.
推荐答案
我不知道手动"是什么意思.您可以选择一个颜色图并足够容易地创建颜色阵列:
I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
plt.scatter(x, y, color=c)
或者您可以使用itertools.cycle
制作自己的颜色循环仪,并使用next
指定要循环显示的颜色,以获得所需的颜色.例如,使用3种颜色:
Or you can make your own colour cycler using itertools.cycle
and specifying the colours you want to loop over, using next
to get the one you want. For example, with 3 colours:
import itertools
colors = itertools.cycle(["r", "b", "g"])
for y in ys:
plt.scatter(x, y, color=next(colors))
请考虑一下,也许也不要在第一个中同时使用zip
是更清洁的方法:
Come to think of it, maybe it's cleaner not to use zip
with the first one too:
colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
plt.scatter(x, y, color=next(colors))
这篇关于在matplotlib上的散点图中为每个系列设置不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!