在Python 3.5.1中使用pylab.scatter和cmap

时间:2016-05-15 23:12:58

标签: python python-2.7 python-3.x matplotlib

当我使用Python2时,我可以绘制图形

from sklearn import datasets
from matplotlib.colors import ListedColormap
circles = datasets.make_circles()

colors = ListedColormap(['red', 'blue'])
pyplot.figure(figsize(8, 8))

pyplot.scatter(map(lambda x: x[0], circles[0]), map(lambda x: x[1], circles[0]), c = circles[1], cmap = colors)

但是当我使用Python3时,我无法做到。我试图改变颜色,但不能。

我收到很多错误:

ValueError: length of rgba sequence should be either 3 or 4

During handling of the above exception, another exception occurred:

ValueError: to_rgba: Invalid rgba arg "[0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 1 1 1 0 1 0 0 1 1 0 1 0 0 0 0 1 0 0 1 0 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 1 1 0 0 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 0 1 1 0 0 0 0 1]" 
length of rgba sequence should be either 3 or 4

During handling of the above exception, another exception occurred:

ValueError: Color array must be two-dimensional

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

问题在于map does not return a list in Python 3。您可以将map传递给list或使用列表推导,它实际上比您的lambda短:

pyplot.scatter([x[0] for x in circles[0]], 
               [x[1] for x in circles[0]], c=circles[1], cmap=colors)

更短的版本完全摆脱了地图:

 pyplot.scatter(*zip(*circles[0]), c=circles[1], cmap=colors)