【问题标题】:How to label the barplot in ggplot with the labels in another test result?如何用另一个测试结果中的标签标记 ggplot 中的条形图?
【发布时间】:2011-05-11 12:26:28
【问题描述】:

我想使用 agricolae 库中的 LSD.test 使用测试的标签输出标记我的绘图,例如 LSD 测试输出(a、b、ab 等)。这是正在运行的示例。

library(ggplot2) 
library(agricolae)
wt<-gl(3,4,108,labels=c("W30","W60","W90")) 
pl<-gl(3,12,108,labels=c("P0","P1","P2")) 
gp<-gl(3,36,108,labels=c("A","B","C")) 

dat<-cbind(
  A=runif(108),
  B=runif(108,min=1,max=10),
  C=runif(108,min=100,max=200),
  D=runif(108,min=1000,max=1500)
) 
dat.df<-data.frame(wt,pl,gp,dat) 
dat.m<-melt(dat.df) 

ggplot(dat.m,aes(x=wt,y=value,group=pl,facet=gp,fill=pl))+         
  stat_summary(fun.y=mean,geom="bar",size=2,position="dodge")+         
  stat_summary(fun.ymin=function(x)(mean(x)-sd(x)/sqrt(length(x))),geom="errorbar", 
  fun.ymax=function(x)(mean(x)+sd(x)/sqrt(length(x))),position="dodge")+
  facet_grid(variable~facet,scale="free_y")+ 
  opts(legend.position="top")+                      
  scale_colour_manual(values = c("red", "blue", "green"))

通常,在其他库中,我测试了数据,并将标签传递给文本图,但是可以在 ggplot 中进行吗?例如,在 stat_summary() 中,使用 fun.y 中的 LSD.test?

【问题讨论】:

  • 该图的运行示例是可以的。但是你能给我们一些实际产生标签的示例代码吗?不知道您要比较哪些...
  • 要做你想做的事,我通常总结 ggplot 之外的数据(例如使用 plyr),然后我将测试中的字母添加到 data.frame 并用 geom_text 绘制字母。

标签: r ggplot2


【解决方案1】:

为此,您必须使用geom_text 创建另一个标签层并指定其自己的数据集。

扩展包lsd.test中的示例agricolae

library(agricolae)
library(ggplot2)

data(sweetpotato)
model <- aov(yield~virus, data=sweetpotato)
lsd <- LSD.test(model,"virus",p.adj="bon")

ggplot() + 
  stat_summary(data=sweetpotato, aes(x=virus, y=yield), fun.y=mean, geom="bar") +
  geom_text(data=lsd, aes(x=trt, y=means, label=round(means, 1)), vjust=0)

【讨论】:

  • 非常感谢@Andrie,你帮了我很多!我试图在我的示例代码中使用您的想法,但没有成功。由于我想测试每一行中的数据(即我的示例中的变量),似乎我需要使用多个因子进行测试,然后将“trt”拆分为单独的因子,并将它们包含在aes() 数据框。这似乎不是那么直截了当,你的意见是什么?而且,我也想知道,有没有办法在一个图中使用星号 (*) 来标记一些单独的条?
【解决方案2】:

你可以试试这个

首先,根据pvalue定义一个向量, 像这样:

padj=ifelse(pval<0.001,'*','')

然后,将 padj 列添加到您的 data.fram,

 head(df)
                                name               type number padj
1                  metabolic process biological_process    968    *
2                 catalytic activity molecular_function    801    *
3         cellular metabolic process biological_process    617    *
4               biosynthetic process biological_process    357    *
5 cellular protein metabolic process biological_process    279     
6                          cytoplasm cellular_component    202    *

最后,将 geom_text 添加到您的绘图中

p <- ggplot(data=df, aes(x=name,y=number,fill=type))+
geom_bar(position=position_dodge())+
scale_fill_brewer(palette="Set2")+
geom_text(aes(label=padj), vjust=0.25,hjust=0.25)
p

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2016-08-16
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多