如何使用 seaborn 相对于行绘制多个条形图?

How to plot several barplots using seaborn with respect to row?

让我们考虑以下数据:

accuracies_in = ([0.5959219858156029, 0.5736842105263158, 0.5670212765957447, 0.3])
accuracies_out = [0.5, 0.6041666666666666, 0.2, 0.4]
auc_out = [0.5182608695652174, 0.6095652173913042, 0.5, 0.7]
algorithm = ["Logistic Regression", "Decision Tree", "Random Forest", "Neural Network"]
frame = pd.DataFrame([accuracies_in, accuracies_out, auc_out])
frame.index = ["accuracies_in", "accuracies_out", "auc_out"]
frame.columns = algorithm

我想要一个条形图来显示这三个特征(accuracies_inaccuarcies_outauc_out)的结果。换句话说,在条形图上我想或多或少像这样对条形图进行分组:

第一组(第一行 - accuracy_in)将包含四个条 - accuracies_in 用于逻辑回归、决策树、随机森林和神经网络。第二组柱状图将再次包含四个柱状图,但这次是第二行 - accuracies_out。最后 - 第三组柱状图将包含四个柱状图,每个柱状图带有 auc_out

你能帮我看看怎么做吗?我搜索了很多问题,但找不到任何可以根据行绘制条形图的内容。你能帮我解决这个问题吗?

你可以使用的是:

X = frame.index

X_axis = np.arange(len(X))
dist = 0.2
plt.figure(figsize=(10,8))
plt.bar(X_axis + (-1)* dist, frame["Logistic Regression"], dist, label = 'accuracies_in')
plt.bar(X_axis + 0 * dist, frame["Decision Tree"], dist, label = 'accuracies_out')
plt.bar(X_axis + 1 * dist, frame["Random Forest"], dist, label = 'auc_out')
plt.bar(X_axis + 2 * dist, frame["Neural Network"], dist, label = 'auc_out')
  
plt.xticks(X_axis, X)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.legend()
plt.show()

输出

除了使用 pandas 内置 plot.bar:

之外,您几乎无事可做
frame.plot.bar()

输入frame:

                Logistic Regression  Decision Tree  Random Forest  Neural Network
accuracies_in              0.595922       0.573684       0.567021             0.3
accuracies_out             0.500000       0.604167       0.200000             0.4
auc_out                    0.518261       0.609565       0.500000             0.7

输出:

您需要将数据框转换为 long form, using pd.melt

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# frame: given dataframe

df = frame.melt(var_name='Algorithm', value_name='Accuracy', ignore_index=False)
sns.set()
sns.barplot(data=df, x=df.index, y='Accuracy', hue='Algorithm')