我正在尝试为以下数据绘制一个框图,我以这种格式给出了数据,这样我就可以让您理解我正在尝试做什么,但实际上,只有RHS部分存在于一个Data.txt文件中
A1 -- 1
A1 -- 2
A1 -- 3
A1 -- 4
A1 -- 5
B1 -- 10
B1 -- 11
B1 -- 12
B1 -- 13
B1 -- 14
C1 -- 20
C1 -- 21
C1 -- 22
C1 -- 23
C1 -- 24
A5 -- 1
A5 -- 2
A5 -- 3
A5 -- 4
A5 -- 5
B5 -- 10
B5 -- 11
B5 -- 12
B5 -- 13
B5 -- 14
C5 -- 20
C5 -- 21
C5 -- 22
C5 -- 23
C5 -- 24
A10 -- 1
A10 -- 2
A10 -- 3
A10 -- 4
A10 -- 5
B10 -- 10
B10 -- 11
B10 -- 12
B10 -- 13
B10 -- 14
C10 -- 20
C10 -- 21
C10 -- 22
C10 -- 23
C10 -- 24但是数据实际上会出现在Data.txt文件中,如下所示
1
2
3
4
5
10
11
12
13
14
20
21
22
23
24
1
2
3
4
5
10
11
12
13
14
20
21
22
23
24
1
2
3
4
5
10
11
12
13
14
20
21
22
23
24现在我想做的是,我想画出A,B,C的BoxPlot,就像这样

但我不知道如何在Python中做到这一点,因为我只是一个初学者,并使用C++进行编码。如果有人能帮助我,我将不胜感激。谢谢。
发布于 2021-02-20 04:24:37
如果可以使用seaborn和pandas,并且文件始终具有相同的结构,则可以在为A-B-C和1-5-10创建两列后对文件进行箱线图
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.read_csv("test.txt", header=None, names=["val"])
df["cat"] = np.tile(np.repeat(["A", "B", "C"], 5), 3)
df["num1_5_10"] = np.repeat([1, 5, 10], 15)
sns.boxplot(data=df, x="num1_5_10", y="val", hue="cat", dodge=False)
plt.show()示例输出:

如果您需要连接线,它将只是另一条线;但是,seaborn会为此点图创建重复的图例条目。因此,如果您想保留图例,我们必须手动删除重复项:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.read_csv("test.txt", header=None, names=["val"])
df["cat"] = np.tile(np.repeat(["A", "B", "C"], 5), 3)
df["num1_5_10"] = np.repeat([1, 5, 10], 15)
ax = sns.boxplot(data=df, x="num1_5_10", y="val", hue="cat", zorder=0.9, dodge=False)
#add the lines connecting the median values
sns.pointplot(data=df, x="num1_5_10", y="val", hue="cat", estimator=np.median, ci=None, markers="None", ax=ax)
#remove duplicate entries, setting the legend outside the graph, new title
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:3], labels[:3], bbox_to_anchor=(1, 1), title="C++ for the win")
plt.tight_layout()
plt.show()示例输出:

奇怪的是,seaborn并不尊重绘图的顺序,所以我们必须操作前面的boxplot中的zorder来获得正确的图形元素顺序。
https://stackoverflow.com/questions/66283023
复制相似问题