首页 文章

带有因子的多列的ggplot boxplot

提问于
浏览
2

我是 ggplot2 的新手,我想在同一个图中绘制多个数字列的boxplot,并将boxplot按最后一列的因子分组,数据帧的 Headers 如下:

id var1 var2 var3 factor

我知道我能做到:

ggplot(df,aes(x=factor,y=var1)+geom_boxplot()

对于每个变量 .

如何与 ggplot2 一起绘制它们?基本图形实用程序 boxplot(df[,-c(id,factor)] 将它们一起绘制 .

2 回答

  • 9

    以下工作“在同一图中绘制多个数字列的箱线图,并按箱子图分组”:

    mm = melt(df, id=c('id','factor.col'))
    ggplot(mm)+geom_boxplot(aes(x=paste(variable,factor.col,sep="_"), y=value))
    

    enter image description here

    数据:

    > df
       id          var1       var2       var3 factor.col
    1   1  0.0562941632  1.3055892 -1.7553986          c
    2   2  0.3187487914 -0.6434729  0.7582403          a
    3   3 -1.0120881740  0.3898366  0.4790115          c
    4   4 -0.7576871261  0.9474247  0.2180341          b
    5   5 -0.2895981608  0.2388043 -0.4407693          a
    6   6  0.0005306311  0.9494667 -0.2604795          c
    7   7  0.2022893934 -0.3095420 -1.9483369          c
    8   8 -0.8179580833 -0.7891642  0.7662824          b
    9   9 -0.7553554525  0.2734337 -0.7145471          b
    10 10  0.4206429078 -0.6171774  0.6274320          c
    >
    

    以下也可以使用:

    ggplot(mm)+geom_boxplot(aes(x=variable, y=value))+facet_grid(.~factor.col)
    

    enter image description here

  • 1

    当您使用 ggplot2 时,您的数据布局需要与基本图形的布局有所不同

    #Your sample data...
    df= data.frame(id = 1:10,
               var1 = rnorm(10),
               var2 = rnorm(10),
               var3= rnorm(10),
               factor.col= LETTERS[1:10]
    )
    # Use the reshape2 package to merge the columns by id and factor.col
    library(reshape2)
    df_long <- melt(df, id=c("id","factor.col"))
    # And now plot the boxplots
    library(ggplot2)
    ggplot(df_long,aes(x=factor.col,y=value)) + geom_boxplot()
    

相关问题