qplot,轴标签和循环

时间:2014-11-10 03:47:58

标签: r ggplot2

我有以下文本文件:trial2.txt  有超过750个数据帧超过60行。 我包括了一部分数据:

status           cst      Hydroxycotinine     A1_2_propanediol      Bacillus 
Smoker           II, lacto      .023                .234            .234
Smoker           I, lacto       .042                .324            .234
Smoker           III lact       .234                .234            .234
Smoker           II, Lacto      .234                .987            .987
Non smoker       II, Lacto      .533                .987            .234
Non smoker       I, lacto       .234                .342            .972
Non smoker       III, lacto     .782                .234            .897

以下是我用来生成我想要的图形的代码,遗憾的是,我无法在保持变量名称的同时遍历数据框:即,这是我生成的代码当我特意命名我想要绘制的变量时的图形:

require(ggplot2)
trial2<-read.table("pl01.txt",header=TRUE,na.strings='',sep='\t')
 qplot(smoking_status,hydroxycotinine,data=trial2,geom="boxplot")+xlab("")+facet_grid(.~cst,scales="free",space="free")+theme_bw()

我无法弄清楚如何在输出中实现列名的同时遍历我的数据框: 代码在这里:

    outputs<-(lapply(trial2[3:5],function(x)qplot(smoking_status,trial2$x,data=trial2,geom="boxplot")+xlab("")+facet_grid(.~cst,scales="free",space="free")+theme_bw()))
    outputs

输出我想要的图表,但丢失了我感兴趣的变量的名称

我很欣赏有关如何简化这一点或更好地生成我想要的结果的任何建议。我意识到我的代码可能不是最有效的。我也试过融化我的数据和其他一些有用的建议但是在修改我的代码时没有一个符合我的需要。

我会发布我的图片的图片,但我还不能发布图片。

1 个答案:

答案 0 :(得分:1)

qplot(...)是一个易于使用的包装器,用于更完整的ggplot函数。我建议您放弃它并深入了解完整的ggplot功能集。这是一种方法(这里只复制了一个图):

library(ggplot2)
plot.col <- function(col) {             # col is the column **name**
  ggplot(trial2, aes(x=status))+
    geom_boxplot(aes_string(y=col))+    # note use of aes_atring(...)
    xlab("")+
    facet_grid(.~cst,scales="free",space="free")+
    theme_bw()
}
lapply(names(trial2)[3:5],plot.col)

enter image description here

关键是aes_string(...)使用了y所需列的名称

相关问题