如何使用 seaborn 制作以下条形图? [复制]
Posted
技术标签:
【中文标题】如何使用 seaborn 制作以下条形图? [复制]【英文标题】:How to make the following barchart with seaborn? [duplicate] 【发布时间】:2021-10-13 07:17:34 【问题描述】:SR=pd.DataFrame([['Linear Regression', 0.9533333333333334, 0.9747081712062257, 0.8255813953488372],['Ridge Classifier', 0.905, 0.9980544747081712, 0.3488372093023256], ['Decision Tree Classifier',0.9883333333333333,0.9922178988326849,0.9651162790697675], ['Random Forest', 0.9916666666666667, 0.9980544747081712, 0.9534883720930233],['XG Boost', 0.9916666666666667, 0.9980544747081712, 0.9534883720930233],['Neural Network', 1.0, 1.0, 1.0]], columns = ['Model', 'Accuracy','Sensitivity','Specificity'])
如何使用 seaborn
和我拥有的 SR
数据框创建附加的条形图(在 Excel 上制作)?
【问题讨论】:
来自duplicate:SR.set_index('Model', inplace=True)
和SR.plot(kind='bar')
【参考方案1】:
首先,您应该使用pandas.melt
重新塑造您的数据框:
SR = pd.melt(frame = SR,
id_vars = 'Model',
var_name = 'Statistic',
value_name = 'value')
所以你得到:
Model Statistic value
0 Linear Regression Accuracy 0.953333
1 Ridge Classifier Accuracy 0.905000
2 Decision Tree Classifier Accuracy 0.988333
3 Random Forest Accuracy 0.991667
4 XG Boost Accuracy 0.991667
5 Neural Network Accuracy 1.000000
6 Linear Regression Sensitivity 0.974708
7 Ridge Classifier Sensitivity 0.998054
8 Decision Tree Classifier Sensitivity 0.992218
9 Random Forest Sensitivity 0.998054
10 XG Boost Sensitivity 0.998054
11 Neural Network Sensitivity 1.000000
12 Linear Regression Specificity 0.825581
13 Ridge Classifier Specificity 0.348837
14 Decision Tree Classifier Specificity 0.965116
15 Random Forest Specificity 0.953488
16 XG Boost Specificity 0.953488
17 Neural Network Specificity 1.000000
然后你可以绘制新的数据框:
sns.barplot(ax = ax, data = SR, x = 'Model', y = 'value', hue = 'Statistic')
完整代码
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
SR=pd.DataFrame([['Linear Regression', 0.9533333333333334, 0.9747081712062257, 0.8255813953488372],['Ridge Classifier', 0.905, 0.9980544747081712, 0.3488372093023256], ['Decision Tree Classifier',0.9883333333333333,0.9922178988326849,0.9651162790697675], ['Random Forest', 0.9916666666666667, 0.9980544747081712, 0.9534883720930233],['XG Boost', 0.9916666666666667, 0.9980544747081712, 0.9534883720930233],['Neural Network', 1.0, 1.0, 1.0]], columns = ['Model', 'Accuracy','Sensitivity','Specificity'])
SR = pd.melt(frame = SR,
id_vars = 'Model',
var_name = 'Statistic',
value_name = 'value')
fig, ax = plt.subplots(figsize = (12, 6))
sns.barplot(ax = ax, data = SR, x = 'Model', y = 'value', hue = 'Statistic')
plt.show()
【讨论】:
以上是关于如何使用 seaborn 制作以下条形图? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何在具有不同 Y 轴的同一个 seaborn 图中很好地制作条形图和线图?
如何在 matplotlib 或 seaborn 中创建带有系列的堆叠条形图? [复制]
如何在 Python 中 Seaborn 的 countplot 中的每个条形上方添加值? [复制]
如何使用 Seaborn 创建 FacetGrid 堆叠条形图?