Matplotlib散点图设置点大小时遇ufunc 'sqrt'类型错误
问题解决:散点图点大小设置报错
你的问题出在数组元素的类型上——所有值都是字符串类型,而且部分字符串前面还带空格,而plt.scatter()的s参数要求传入数值(int/float),字符串无法被内部的数值计算(比如报错里提到的sqrt运算)处理,所以抛出了类型错误。
解决步骤
把数组中的字符串转换成数值类型,同时清理掉字符串前后的空格:
- 对x坐标、y坐标、点大小分别用
float()或int()转换,转换前用strip()去除多余空格 - 可以在循环内直接转换,也可以提前预处理整个数组提升效率
修改后的代码示例
import matplotlib.pyplot as plt # 你的原始数组 convertedResults = [['50', ' 50', ' 0.6352952'], ['60', ' 50', ' 2.8389171199999996'], ['70', ' 50', ' 2.8389171199999996'], ['50', ' 60', ' 0.6352952']] for item in convertedResults: x = float(item[0].strip()) y = float(item[1].strip()) size = float(item[2].strip()) plt.scatter(x, y, s=size) plt.show()
批量预处理优化(适合大数据组)
import matplotlib.pyplot as plt convertedResults = [['50', ' 50', ' 0.6352952'], ['60', ' 50', ' 2.8389171199999996'], ['70', ' 50', ' 2.8389171199999996'], ['50', ' 60', ' 0.6352952']] # 批量转换所有元素为数值类型 processed_data = [[float(val.strip()) for val in row] for row in convertedResults] # 一次性提取坐标和大小绘图,更高效 x_vals = [row[0] for row in processed_data] y_vals = [row[1] for row in processed_data] sizes = [row[2] for row in processed_data] plt.scatter(x_vals, y_vals, s=sizes) plt.show()
内容的提问来源于stack exchange,提问作者Chopper
相关产品推荐
相关产品推荐

