如何使用 .boxplot 函数修复 matplotlib 中 pyplot 中的“X 必须具有 2 个或更少维度”错误?

T. *_*ter 1 python matplotlib boxplot

我想使用 python 中 matplotlib 中的 pyplot 创建一个带有 2 个箱线图的图形。

我正在使用鸢尾花数据集,该数据集提供了三种类型 150 朵花的花瓣长度:Setosa、Versicolor、Virginica。我想为 Setosa 的花瓣长度创建一个箱线图,为 Versicolor 的花瓣长度创建一个箱线图,所有这些都在同一个图上。

我的代码基于本教程:https://matplotlib.org/gallery/pyplots/boxplot_demo_pyplot.html#sphx-glr-gallery-pyplots-boxplot-demo-pyplot-py

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from matplotlib import pyplot as plt

# From the iris dataset I create a dataframe which contains only the features 
# of the flowers (sepal length, sepal width, petal length, petal width and the 
# flower type. 

data = load_iris()
X= data["data"]
y = data ["target"]
iris=pd.DataFrame(X)
iris["target"]=y
iris.columns=data['feature_names']+["target"]
iris["target"]=iris["target"].apply(lambda x:'Setosa' if x == 0 else 'Versicolor' if x == 1 else 'Virginica')

# I create my sub-dataframes which each contain the petal length of one type of flower 
ar1 = np.array(iris.loc[lambda iris: iris["target"] == "Setosa", ["petal width (cm)"]])
ar2 = np.array(iris.loc[lambda iris: iris["target"] == "Versicolor", ["petal width (cm)"]])

# This works: 
fig, ax = plt.subplots()
ax.boxplot(ar1)
plt.show()

# But this doesn't work:
data1 = [ar1, ar2] 
fig, ax = plt.subplots()
ax.boxplot(data1)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我期望一个带有 2 个箱线图的图形。相反,我收到错误:“ValueError:X 必须具有 2 个或更少的维度”。然而 ar1 和 ar2 有 2 个维度,与上面提到的 matplotlib 示例中所示完全相同。

非常感谢您的帮助,

Imp*_*est 7

问题是

ar1 = np.array(iris.loc[lambda iris: iris["target"] == "Setosa", ["petal width (cm)"]])
Run Code Online (Sandbox Code Playgroud)

创建形状为 的二维数组(50,1)。所以你能做的就是先压平数组,

data1 = [ar1.flatten(), ar2.flatten()] 
fig, ax = plt.subplots()
ax.boxplot(data1)
Run Code Online (Sandbox Code Playgroud)