问题描述
背景:
- 在 windows 系统的 jupyter notebook 中,使用 Matplotlib(版本3.5.2) 中的 scatter 函数绘制散点图时,报错如下:
ValueError: s must be a scalar, or float array-like with the same size as x and y
具体:
- 示例:画 10 种大小,100 种颜色的散点图
import matplotlib.pyplot as plt
import numpy as np
# 画 10 种大小, 100 种颜色的散点图?
np.random.seed(0)
x=np.random.rand(100)
y=np.random.rand(100)
colors=np.random.rand(100) # 100 种颜色
size=np.random.rand(10)*1000 # 10 种大小
plt.scatter(x,y,c=colors,s=size,alpha=0.7)
plt.show()
解决方法
分析:
- 在报错信息中寻找错误原因
File D:\AllApp\Miniconda3\lib\site-packages\matplotlib\axes\_axes.py:4371, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
4367 s = np.ma.ravel(s)
4368 if (len(s) not in (1, x.size) or
4369 (not np.issubdtype(s.dtype, np.floating) and
4370 not np.issubdtype(s.dtype, np.integer))):
-> 4371 raise ValueError(
4372 "s must be a scalar, "
4373 "or float array-like with the same size as x and y")
4375 # get the original edgecolor the user passed before we normalize
4376 orig_edgecolor = edgecolors
ValueError: s must be a scalar, or float array-like with the same size as x and y
处理:
- 让 scatter() 函数接收的数组参数长度相同
import matplotlib.pyplot as plt
import numpy as np
# 绘制 100 种大小 100 种颜色的散点图
np.random.seed(66666) # 设定随机种子(每次执行结果一样)
x=np.random.rand(100) # 生成一百个随机点(标准正态分布)
y=np.random.rand(100)
colors=np.random.rand(100)
size=np.random.rand(100)*1000 # 乘以1000是为了让数值变大些
plt.scatter(x,y,c=colors,s=size,alpha=0.7) # alpha:透明度
plt.show()