R: Plot multiple box plots using columns from data frame

后端 未结 3 1304
慢半拍i
慢半拍i 2020-12-10 02:54

I would like to plot an INDIVIDUAL box plot for each unrelated column in a data frame. I thought I was on the right track with boxplot.matrix from the sfs

相关标签:
3条回答
  • 2020-12-10 03:12

    From ?boxplot we see that we have the option to pass multiple vectors of data as elements of a list, and we will get multiple boxplots, one for each vector in our list.

    So all we need to do is convert the columns of our matrix to a list:

    m <- matrix(1:25,5,5)
    boxplot(x = as.list(as.data.frame(m)))
    

    If you really want separate panels each with a single boxplot (although, frankly, I don't see why you would want to do that), I would instead turn to ggplot and faceting:

    m1 <- melt(as.data.frame(m))
    library(ggplot2)
    ggplot(m1,aes(x = variable,y = value)) + facet_wrap(~variable) + geom_boxplot()
    
    0 讨论(0)
  • 2020-12-10 03:13

    You could use the reshape package to simplify things

    data <- data.frame(v1=rnorm(100),v2=rnorm(100),v3=rnorm(100), v4=rnorm(100))
    library(reshape)
    meltData <- melt(data)
    boxplot(data=meltData, value~variable)
    

    or even then use ggplot2 package to make things nicer

    library(ggplot2)
    p <- ggplot(meltData, aes(factor(variable), value)) 
    p + geom_boxplot() + facet_wrap(~variable, scale="free")
    
    0 讨论(0)
  • 2020-12-10 03:21

    I used iteration to do this. I think perhaps I wasn't clear in the original question. Thanks for the responses none the less.

    par(mfrow=c(2,5))
    for (i in 1:length(plotdata)) {
            boxplot(plotdata[,i], main=names(plotdata[i]), type="l")
    
    }
    
    0 讨论(0)
提交回复
热议问题