How to create 2x2 bar plot - with side by side pairwise bar in R

后端 未结 2 1173
独厮守ぢ
独厮守ぢ 2021-01-17 02:41

I have the following data:

  Method    Metric        E0        E1        E2        E4
1     M1 Precision 0.9661017 0.9622642 1.0000000 0.9655172
2     M2 Pr         


        
相关标签:
2条回答
  • 2021-01-17 03:12

    Here you go:

    Import:

    dat <- read.table(text="Method  Metric  E0  E1  E2  E4
    M1  Precision   0.9661017   0.9622642   1   0.9655172
    M2  Precision   0.533   0.535   0.378   0.214
    M1  Recall  0.9736842   0.9736842   0.9473684   0.9473684
    M2  Recall  1   1   1   0.667",header=TRUE)
    

    Define a layout and some colours:

    layout(matrix(c(1,2,5,3,4,5),nrow=2,byrow = TRUE))
    #     [,1] [,2] [,3]
    #[1,]    1    2    5
    #[2,]    3    4    5
    barcols <- c("red","blue")
    

    Generate some plots:

    sapply(3:6, 
      function(x) {
        bp <- barplot(matrix(dat[,x],nrow=2,byrow=TRUE),beside=TRUE,col=barcols)
        title(main=names(dat[x]))
        axis(1,at=colMeans(bp),c("M1","M2"),lwd=0,lwd.tick=1)
        abline(h=0)
      }
    )
    

    Add a legend:

    plot(NA,xlim=c(0,1),ylim=c(0,1),ann=FALSE,axes=FALSE)
    legend(0,0.6,c("Precision","Recall"),fill=barcols,cex=1.5)
    

    Result:

    enter image description here

    0 讨论(0)
  • 2021-01-17 03:25

    I realize you are trying to avoid external libraries, but ggplot was designed to make this easy.

    library(ggplot2)
    library(reshape2)
    
    gg <- melt(df,id=1:2)
    ggplot(gg) +
      geom_bar(aes(x=Method, y=value, fill=Metric), stat="identity",
               position="dodge")+facet_wrap(~variable)
    

    0 讨论(0)
提交回复
热议问题