【问题标题】:TypeError: ufunc 'sqrt' not supported for the input types when plotting a colormap in basemapTypeError:在底图中绘制颜色图时,输入类型不支持 ufunc 'sqrt'
【发布时间】:2019-09-30 13:58:53
【问题描述】:

我想使用颜色图绘制关于房价和地理坐标之间关系的散点图。

from mpl_toolkits.basemap import Basemap


lats = df['latitude'].as_matrix()
lons = df['longitude'].as_matrix()

zoom_scale = 0

bbox = [np.min(lats)-zoom_scale,np.max(lats)+zoom_scale,\
        np.min(lons)-zoom_scale,np.max(lons)+zoom_scale]

plt.figure()

m = Basemap(projection='merc',llcrnrlat=bbox[0],urcrnrlat=bbox[1],\
    llcrnrlon=bbox[2],urcrnrlon=bbox[3],resolution='i')

m.drawcoastlines()
m.drawrivers()

x,y = m(lons,lats)
cm = plt.cm.get_cmap('coolwarm')
plot = m.scatter(x,y,'o',c = df['price'],cmap=cm)
plt.colorbar(plot)
plt.title("House Price with Geographic Coordinate")
plt.show()

控制台给出一个TypeError:


TypeError Traceback(最近一次调用最后一次)在

     28 x,y = m(lons,lats)
     29 cm = plt.cm.get_cmap('coolwarm')
---> 30 plot = m.scatter(x,y,'o',c = df['price'],cmap=cm)
     31 plt.colorbar(plot)
     32 plt.title("House Price with Geographic Coordinate")

....

/anaconda3/lib/python3.7/site-packages/matplotlib/collections.py in set_sizes(self, sizes, dpi)
    872             self._sizes = np.asarray(sizes)
    873             self._transforms = np.zeros((len(self._sizes), 3, 3))
--> 874             scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
    875             self._transforms[:, 0, 0] = scale
    876             self._transforms[:, 1, 1] = scale

TypeError: 输入类型不支持 ufunc 'sqrt',并且根据转换规则 ''safe'' 无法安全地将输入强制转换为任何支持的类型

我该如何解决这个问题? 最好的问候

【问题讨论】:

  • plot = m.scatter(x,y,'o',c = df['price'],cmap=cm)这一行,df['price']的内容是什么?如果你在没有c = df['price'] 的情况下运行代码,它会工作吗?
  • 我打算画出每个坐标的房价,看看它们之间是否有任何关系。如果我删除 c = df [ 'price' ] 和 cmap 设置,控制台仍然给我同样的错误。
  • 尝试不带 'o',这在 scatter 中是不必要的。

标签: python matplotlib-basemap colormap


【解决方案1】:

plt.scatter 行中取出'o'

【讨论】:

    【解决方案2】:

    这是scatter 绘图的问题。这可以通过明确提及您提供的参数来解决。

    所以,改变

    plot = m.scatter(x,y,'o',c = df['price'],cmap=cm)
    

    plot = m.scatter(x,y,marker='o',cmap=cm)
    

    一些免费提示:在使用散点图时,避免直接命名函数参数,即,

    plt.scatter(x,y,'blue')
    

    相当使用

    plt.scatter(x,y,color='blue')
    

    此外,要在您的日常编程中包含调试,首先将散点图简单地绘制为plot = m.scatter(x,y)。然后,继续增加颜色、形状等属性。

    注意:折线图中不容易出现此错误(plt.plot(x,y,'red') 会起作用)

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 2020-09-29
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2018-03-09
      • 2020-02-18
      • 2020-02-16
      相关资源
      最近更新 更多