python - 如何使用 .boxplot 函数在 matplotlib 的 pyplot 中修复“X 必须有 2 个或更少的维度”错误?
问题描述
我想在 python 中使用 matplotlib 中的 pyplot 创建一个带有 2 个箱线图的图形。
我正在使用 iris 数据集,该数据集提供了三种类型的 150 朵花的花瓣长度:Setosa、Versicolor、Virginica。我想为 Setosa 的花瓣长度创建一个箱线图,为 Versicolor 的花瓣长度创建一个箱线图,所有这些都在同一个图中。
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 示例中所示的完全一样。
非常感谢您的帮助,
解决方案
问题是
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)
推荐阅读
- ios - 如何捕捉可访问性焦点的变化?
- jquery - jqGrid将多选列过滤器添加到特定列
- javascript - 试用 AWS-Amplify ->“npm start”不起作用
- angular - 将填充有字符串的模型解析为另一个填充有日期的模型
- javascript - 如何将 HTML 元素值设置为用户输入的值
- c++ - 将无符号整数分配给宽度较小的有符号整数时会发生什么?
- learning-locker - 多个代理的活动查询语句
- eclipse - 如何使用 JDK 11/Maven/Eclipse IDE 运行 JavaFX 应用程序
- sql-server - 如何在使用 Oracle DB 和 SQL Server DB 之间切换实体框架?
- jquery - 使用多个模型时的 Asp.net Core 发布表单数据