r - 如何在QPLOT中使 `geom_text`识别 `aes`(R编程)

标签 r plot ggplot2

我有一个看起来像this的数据

ensg mirna_hgc time value perc id
ENSG00000211521 MIR665 x 89 2.07612456747405 1
ENSG00000207787 MIR98 x 73 1.73010380622837 2
...
ENSG00000207827 MIR30A y 99 21.4532871972318 288
ENSG00000207757 MIR93 y 94 1.73010380622837 289

我想做的是创建一个上面带有标签的分面图。 可以从 perc 列轻松调用该标签。

使用此代码:

dat.m <- read.delim("http://dpaste.com/1271039/plain/",header=TRUE,sep=" ")

qplot(value, data=dat.m,facets=time~.,binwidth=1,main="")+
xlab("Value")+ ylab("Count")+
theme(legend.position="none")+
stat_bin(aes(value,label=sprintf("%.01f",perc)),geom="text")

但它给了我这个错误:

Error: geom_text requires the following missing aesthetics: label

我想做的是生成这个图: enter image description here

最佳答案

您的问题部分出现

  • 因为您正在使用 qplot (这使得事情比您需要的更加困惑)。

  • 您已设置binwidth = 2,这意味着每个直方图条形图(可能)基于 2 个 value 值。 perc 到值的 1 对 1 映射现在是 perc 到分箱值的 2 到 -1 映射

使用 plyr 继续 hadleyesque 实现,我们可以在绘图之前进行聚合

library(plyr)
agg.data <-  ddply(dat.m, .(value,time), summarize, p = unique(perc), n = length(perc))

ggplot(agg.data, aes(x= value)) + 
 geom_bar(aes(y = n),stat='identity') + 
 facet_grid(time~.) + 
 geom_text(aes(y=n, label = sprintf('%.01f',p)),vjust=-1,size=3)

enter image description here

如果您想使用geom_histogram并显示与每个条形相关的比例,这可以很容易地完成,但您需要使用stat_bin创建的值(即..密度..,这是分配给每个条形的比例)

ggplot(dat.m, aes(x= value)) + 
  geom_histogram(binwidth=2) +  
  facet_grid(time~.) + 
  stat_bin(aes(y = ..count.., label = sprintf('%.01f', 100 * ..density..)),
           binwidth=2,geom='text',vjust = -1)

enter image description here

并使用 ifelse 替换没有标签的 0.0 (使用一些定义技巧来避免重复测试。

ggplot(dat.m, aes(x= value)) + 
   geom_histogram(binwidth=2) +  facet_grid(time~.) + 
   stat_bin(aes(y = ..count.., 
     label = ifelse(test = (xxx <- sprintf('%.01f', 100 * ..density..))=='0.0','',xxx)),
     binwidth=2,geom='text',vjust = -0.7)

enter image description here

请注意,您可以使用 qplot 得到相同的结果

qplot(value, data=dat.m,facets=time~.,binwidth=2,main="")+
     xlab("Value")+ ylab("Count")+
     theme(legend.position="none")+
     stat_bin(aes(value,label=ifelse(test = (xxx <-  
       sprintf("%.01f",..density..*100))=='0.0','',xxx)),geom="text",binwidth=2,vjust = -0.7)

关于r - 如何在QPLOT中使 `geom_text`识别 `aes`(R编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17310612/

相关文章:

r - 使用 "dimnames"= List of 2 格式化动物园对象

r - 如何使用不同的投影裁剪光栅

plot - 将误差线设为转换后的值

r - 有没有办法去除ggplot2中图例的边框?

r - 在 R 中使用 ggplot2 的多行多错误条

r - 无法在 R 中从 GitHub 加载 *.Rda 文件

r - 使用 dplyr 对多列求和时忽略 NA

r 通过查找表替换字符串中的文本

r - 如何阻止使用 lattice 包制作的 R 中的水平图的一部分?

r - ggplot2 中的数字格式轴标签?