首页 > 解决方案 > 如何使用 .boxplot 函数在 matplotlib 的 pyplot 中修复“X 必须有 2 个或更少的维度”错误?

问题描述

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

我正在使用 iris 数据集,该数据集提供了三种类型的 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()

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

非常感谢您的帮助,

标签: pythonmatplotlibboxplot

解决方案


问题是

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

创建一个二维数组 shape (50,1)。所以你可以做的是先展平阵列,

data1 = [ar1.flatten(), ar2.flatten()] 
fig, ax = plt.subplots()
ax.boxplot(data1)

推荐阅读