问题| Matplotlib 中绘制散点图:ValueError: s must be a scalar, or ... with the same size as x and y @Python

在Windows的Jupyter Notebook中使用Matplotlib 3.5.2绘制散点图时遇到ValueError。错误提示`s`必须是标量或与`x`和`y`尺寸相同的浮点数数组。问题出在`size`数组长度不匹配。修正代码将`size`数组长度调整为与`x`和`y`相同,即可解决该错误。示例代码展示了如何正确绘制100种大小和颜色的散点图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

背景:

  • 在 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()

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值