matplotlib 错误:x 和 y 的大小必须相同

Posted

技术标签:

【中文标题】matplotlib 错误:x 和 y 的大小必须相同【英文标题】:matplotlib error: x and y must be the same size 【发布时间】:2019-08-20 07:17:32 【问题描述】:

如何解决“ValueError: x and y must be the same size”错误?

代码的想法是从不同的温度传感器和 NO 数据应用多元线性回归模型。训练模型并查看它们之间的相关结果,以及整体预测。

from sklearn import linear_model
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pandas as pd
import matplotlib.pyplot as plt

# Name of de file
filename = 'NORM_AC_HAE.csv'
file = 'NORM_NABEL_HAE_lev1.csv'

# Read the data
data=pd.read_csv(filename)
data_other=pd.read_csv(file)

col = ['Aircube.009.0.no.we.aux.ch6', 'Aircube.009.0.sht.temperature.ch1']
X = data.loc[:, col]
Y = data_other.loc[:,'NO.ppb']

# Fitting the Liner Regression to training set
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, train_size = 0.6, random_state = np.random.seed(0))
mlr = LinearRegression()
mlr.fit(X_train, y_train)

# Visualization of the test set results
plt.figure(2)
plt.scatter(y_test, X_test) #The VALUE ERROR appears here

错误代码是:

Traceback (most recent call last):
  File "C:\Users\andre\Desktop\UV\4o\TFG\EMPA\dataset_Mila\MLR_no_temp_hae_no.py", line 65, in <module>
    plt.scatter(y_test, X_test)
  File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\pyplot.py", line 2864, in scatter
    is not None else ), **kwargs)
  File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\__init__.py", line 1810, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\axes\_axes.py", line 4182, in scatter
    raise ValueError("x and y must be the same size")
ValueError: x and y must be the same size
[Finished in 6.9s]

【问题讨论】:

你的X_test.shape 是什么?见***.com/questions/41659535/… X_test.shape = [36648 行 x 2 列] 【参考方案1】:

X_test.shape = [36648 行 x 2 列]

plt.scatter(此处为y_testX_test)中的两个数据参数必须是一维数组;来自docs:

x, y : array_like, 形状 (n, )

在这里您尝试为X_test 传递一个二维矩阵,因此会出现不同大小的错误。

您无法获得带有数组/向量的矩阵的散点图;你可以做的是生成两个单独的散点图,一个用于X_test 中的每一列:

plt.figure(2)
plt.scatter(y_test, X_test.iloc[:,0].values)

plt.figure(3)
plt.scatter(y_test, X_test.iloc[:,1].values)

【讨论】:

以上是关于matplotlib 错误:x 和 y 的大小必须相同的主要内容,如果未能解决你的问题,请参考以下文章

散点图错误:“x 和 y 的大小必须相同”但它们的大小相同

matplotlib 折线图

matplotlib scatter Valueerror: 'c' 参数有 n 个元素,不能与大小为 m 的 'x' 和 'y' 一起使用

PyPlot 错误“X 和 Y 的大小必须相同”,我在网上找到的所有内容都不起作用

matplotlib 散点图

Matplotlib的'Float'错误