You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在函数内用*args绘制多散点子图时遇ValueError问题求助

问题原因与解决方法

报错原因

你传入的X和Y是形状为(8,2)的二维数组,当执行ax.scatter(*xy)时,*xy会把二维数组按行拆分成8个长度为2的一维数组。scatter函数会将前两个数组当作x、y坐标,第三个数组当作点大小参数s,但这个参数的长度和x/y不匹配,因此抛出ValueError。

解决方法

有两种简单的修复方式:

方法1:在函数内直接提取数组的两列作为x和y

修改test函数里的scatter调用,明确取数组的第一列和第二列分别作为x轴和y轴数据:

import pandas as pd
import numpy as np
from matplotlib.pyplot import plt

x = np.array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], 
              [0.3, 0.5, 0.6, 0.2, 0.4, 0.5, 0.6, 0.5, 0.8, 0.9, 0.9, 0.8, 0.2, 0.1, 0.5, 0.6],
              ['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']])

values = pd.DataFrame(x.T, columns=['a', 'b', 'c'])

X = values[values['c'] == 'r'].iloc[:, 0:2].values
Y = values[values['c'] == 'b'].iloc[:, 0:2].values

def test(*args):
    figs, axs = plt.subplots(1, 2, figsize=(8, 8))
    for xy, ax in zip(args, axs.flat):
        # 提取数组的第一列和第二列作为x、y
        ax.scatter(xy[:, 0], xy[:, 1])

test(X, Y)
plt.show()

方法2:传入参数时提前拆分成(x,y)元组

调用函数前,把X和Y拆分成x、y的元组,这样函数内的*xy就能正确解包:

import pandas as pd
import numpy as np
from matplotlib.pyplot import plt

x = np.array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], 
              [0.3, 0.5, 0.6, 0.2, 0.4, 0.5, 0.6, 0.5, 0.8, 0.9, 0.9, 0.8, 0.2, 0.1, 0.5, 0.6],
              ['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']])

values = pd.DataFrame(x.T, columns=['a', 'b', 'c'])

X = values[values['c'] == 'r'].iloc[:, 0:2].values
Y = values[values['c'] == 'b'].iloc[:, 0:2].values

def test(*args):
    figs, axs = plt.subplots(1, 2, figsize=(8, 8))
    for xy, ax in zip(args, axs.flat):
        ax.scatter(*xy)

# 提前拆分X和Y为(x,y)元组
test((X[:,0], X[:,1]), (Y[:,0], Y[:,1]))
plt.show()

内容的提问来源于stack exchange,提问作者Emil11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:15:34