【问题标题】:Creating grouped bar plot for model comparison in R在 R 中为模型比较创建分组条形图
【发布时间】:2023-03-26 10:15:01
【问题描述】:

我在创建分组条形图以可视化两个模型的性能时遇到问题。我已将来自 k 折交叉验证的数据存储到名为 modelcomp 的数据框中:

modelcomp
         n_comp  Accuracy      Sens      Spec
1 20 components 0.7754178 0.8006006 0.7548485
2  5 components 0.7716294 0.7783033 0.7663636

我想要达到的结果尽可能类似于以下(用excel制作)

.

感谢您的帮助!

【问题讨论】:

  • 试试barplot(as.matrix(d[-(1:2)]), beside=TRUE)

标签: r plot graph bar-chart


【解决方案1】:

这够近了吗?

library(ggplot2)
library(cowplot)
library(dplyr)
library(reshape2)

df <- data.frame(n_comp=c('20 components','5 components'),
                 Accuracy=c(0.7754178,0.7716294),
                 Sens=c(0.8006006,0.7783033),
                 Spec=c(0.7548485,0.7663636))
reshape2::melt(df, id.vars = "n_comp") %>% 
    mutate(n_comp = relevel(factor(n_comp), "5 components")) %>% 
ggplot(aes(x=variable, y=value, fill=n_comp, 
           label = scales::percent(value, accuracy=.1), width=.6)) +
    geom_bar(stat='identity', position=position_dodge2(width=.8, padding=.2)) +
    geom_text(position = position_dodge(.6), vjust=-0.5, size=5) +
    theme_minimal_hgrid()+
    theme(legend.position = 'bottom', 
          legend.title = element_blank(),
          text = element_text(size = 18),
          axis.text = element_text(size = 18),
          plot.title = element_text(hjust = 0.5)) +
    labs(x=NULL, y=NULL, title = "Model Comparison")+
    coord_cartesian(ylim = c(.6, .85)) +
    scale_fill_manual(values = c("#4472c4", "#eb7c31"))

reprex package (v0.3.0) 于 2020-08-17 创建

【讨论】:

  • 谢谢,太好了!
【解决方案2】:

试试这个:

library(tidyverse)
#Data
df <- data.frame(n_comp=c('20 components','5 components'),
                 Accuracy=c(0.7754178,0.7716294),
                 Sens=c(0.8006006,0.7783033),
                 Spec=c(0.7548485,0.7663636),stringsAsFactors = F)
#Melt
df1 <- df %>% pivot_longer(cols = -n_comp)
#Plot
ggplot(df1,aes(x=name,y=value,fill=n_comp,label=paste0(100*round(value,3),'%')))+
  geom_bar(stat='identity',position = 'dodge')+
  geom_text(position = position_dodge(0.9),vjust=-0.25)+
  theme(legend.position = 'bottom')

输出:

【讨论】:

    【解决方案3】:

    使用@Duck 的数据框。这将构建一个基本图形条形图:

    out <- barplot(as.matrix(df[, -1]), ylab="Value", ylim=c(0, .9), main="Model Comparison", 
         beside=TRUE, col=c("blue", "dark orange"))
    legend(2.5, -.07, df$n_comp, ncol=2, xpd=NA, fill=c("blue", "dark orange"), bty="n")
    x <- as.vector(out)
    y <- unlist(df[, -1])
    pct <- paste(round(unlist(df[, -1])*100, 1), "%")
    text(x, y, pct, pos=3, xpd=NA)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2019-04-10
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多