【问题标题】:pylab: plotting points with colorspylab:用颜色绘制点
【发布时间】:2017-03-07 05:30:21
【问题描述】:

我正在尝试在二维空间中绘制点,插入标签以及设置每个点的颜色(不依赖于标签)。 第一次尝试,不考虑标签是:

import pylab
x = [-0.01611772,  1.51755901, -0.64869352, -1.80850313, -0.11505037]
y = [ 0.04845168, -0.45576903,  0.62703651, -0.24415787, -0.41307092]
colors = ['b', 'g', 'r', 'b', 'r']

for k in range(len(x)):
    pylab.scatter(x[k],y[k],colors[k])

它返回一个不符合执行绘图所需操作的错误:

Traceback (most recent call last):
  File "<pyshell#1>", line 12, in <module>
    pylab.scatter(x[k],y[k],colors[k])
  File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 3258, in scatter
    edgecolors=edgecolors, data=data, **kwargs)
  File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\__init__.py", line 1818, in inner
    return func(ax, *args, **kwargs)
  File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\axes\_axes.py", line 3866, in scatter
    alpha=alpha
  File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\collections.py", line 833, in __init__
    self.set_sizes(sizes)
  File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\collections.py", line 806, in set_sizes
    scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

有人有想法吗?

【问题讨论】:

    标签: python matplotlib colors label


    【解决方案1】:

    这里不需要使用 for 循环。只需将您的颜色列表传递给 pylab.scatter 函数:

    import pylab
    
    x = [-0.01611772,  1.51755901, -0.64869352, -1.80850313, -0.11505037]
    y = [ 0.04845168, -0.45576903,  0.62703651, -0.24415787, -0.41307092]
    
    colors = ['b', 'g', 'r', 'b', 'r']
    
    pylab.scatter(x, y, c=colors)
    
    pylab.show()
    

    这会产生以下图表:

    【讨论】:

      【解决方案2】:

      改变

      pylab.scatter(x[k],y[k],colors[k]) 
      

      pylab.scatter(x = x[k],y = y[k],c = colors[k])
      

      【讨论】:

      • 好的。我只是想指出,使用 for 循环很好,以防从当前答案中不明显。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多