Matplotlib散点图ValueError报错求助:参数s不符合要求
问题:Matplotlib绘制散点图时抛出ValueError
原代码
import matplotlib.pyplot as graph data = [147,96,106,81,48,37,15,25,41,99,160,145] months = ["1/22", "2/22", "3/22", "4/22", "5/22", "6/22", "7/22", "8/22", "9/22", "10/22","11/22", "12/22"] data2 = [48,50,54,59,66,71,77,78,71,61,52,47] graph.title("Seattle (Rain Fall vs Temperature)", fontsize = 14) graph.xlabel("Months", fontsize = 14) graph.ylabel("Weather Level", fontsize = 14) graph.tick_params(axis='both',labelsize = 9) graph.scatter(data, months, color="blue", label = "Average Rain Fall") graph.scatter(data2, months, color="red", label = "Average Temperature") graph.legend() graph.scatter(data, data2, months) graph.show()
报错信息
runfile('C:/Users/dddst279/My Files/Google Drive/My Drive/Scatter Graph.py', wdir='C:/Users/dddst279/My Files/Google Drive/My Drive') Traceback (most recent call last): File "C:\Users\dddst279\My Files\Google Drive\My Drive\Scatter Graph.py", line 14, in <module> graph.scatter(data, data2, months) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2819, in scatter __ret = gca().scatter( File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 1412, in inner return func(ax, *map(sanitize_sequence, args), **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 4371, in scatter raise ValueError( ValueError: s must be a scalar, or float array-like with the same size as x and y
错误原因
错误出在代码行graph.scatter(data, data2, months):
Matplotlib的scatter函数第三个参数是s,用于指定散点的大小,要求是标量或者和x、y长度一致的浮点数组。你传入的months是字符串列表,完全不符合s的参数要求,因此触发了这个ValueError。
解决方案
根据你的需求,有两种处理方式:
方式1:如果想给降雨量与温度的对应点添加月份标签
删除错误的scatter调用,改用annotate循环为每个点添加标签:
# 替换原错误行 for x, y, month in zip(data, data2, months): graph.annotate(month, (x, y), textcoords="offset points", xytext=(0,10), ha='center')
方式2:如果该代码行是误添加的
直接删除graph.scatter(data, data2, months)这一行即可,前面的代码已经完成了降雨量、温度与月份的散点绘制。
修正后的完整代码示例
import matplotlib.pyplot as graph data = [147,96,106,81,48,37,15,25,41,99,160,145] months = ["1/22", "2/22", "3/22", "4/22", "5/22", "6/22", "7/22", "8/22", "9/22", "10/22","11/22", "12/22"] data2 = [48,50,54,59,66,71,77,78,71,61,52,47] graph.title("Seattle (Rain Fall vs Temperature)", fontsize = 14) graph.xlabel("Months", fontsize = 14) graph.ylabel("Weather Level", fontsize = 14) graph.tick_params(axis='both',labelsize = 9) graph.scatter(data, months, color="blue", label = "Average Rain Fall") graph.scatter(data2, months, color="red", label = "Average Temperature") # 添加月份标签(可选) for x, y, month in zip(data, data2, months): graph.annotate(month, (x, y), textcoords="offset points", xytext=(0,10), ha='center') graph.legend() graph.show()
内容的提问来源于stack exchange,提问作者eleven
相关产品推荐
相关产品推荐

