4

使用此代码

library(ggplot2)
ggplot( dat,aes(x=factor(group),y=difference) ) +
  geom_bar( width=.75,aes(fill=as.factor(Mutation)),stat="identity",
            position="dodge") +
  geom_text(aes(label=Mutation),position=position_dodge(height=0.9),angle=90)+
  theme_bw() + 
  theme(legend.position="none")

我生成流动的情节。如您所见,某些文本不在条的中心。我尝试了一些选项,例如hjustvjust或玩dodge width,但没有成功。有人可以帮我把文字放在酒吧的中心吗?

在下图中,我们遇到 group = 1 ,3,8,9,... 的问题

在此处输入图像描述

这是我的数据:

dat <-  structure(list(Mutation = structure(1:21, .Label = c("2rN7y", 
"2wTys", "8ElEj", "8esgR", "8ppm9", "BkuXt", "bM5sv", "c7KTn", 
"dnBl6", "F5nhO", "fFpM6", "hMpSW", "HxAh9", "KDI0t", "qZTSa", 
"rOONr", "Tf2kX", "TGDZE", "tLdje", "XsGz6", "XTGN1"), class = "factor"), 
    difference = c(2.1499193357556, 0.27602347826589, -0.22889581513082, 
    -0.77297822818092, -0.468200478640476, -0.735026155784277, 
    -0.900791750580477, -1.33435362820732, 0.412022274758476, 
    0.495870479997156, 0.793585307678721, 1.22839278213642, -1.0700682293443, 
    0.63436212480624, -0.152410633064764, 1.23397624015726, -0.520869343832941, 
    1.62320252173067, -0.24168976773895, -1.04897550447309, 1.68588724420516
    ), position = c(4, 4, 3, 2, 3, 3, 2, 3, 2, 5, 2, 2, 2, 5, 
    5, 5, 2, 4, 5, 4, 2), group = c(0L, 0L, 1L, 2L, 3L, 3L, 4L, 
    5L, 6L, 7L, 8L, 8L, 8L, 9L, 9L, 9L, 10L, 11L, 12L, 13L, 14L
    )), .Names = c("Mutation", "difference", "position", "group"
), row.names = c(11L, 2L, 19L, 10L, 9L, 21L, 20L, 12L, 16L, 13L, 
17L, 1L, 6L, 15L, 18L, 14L, 4L, 5L, 8L, 3L, 7L), class = "data.frame")
4

2 回答 2

3

我使用@cyclondude 的想法,并使用它tapply来创建一个调整向量。

dat$group_adjust <- unlist(tapply(dat$group,dat$group,
       function(x) if(length(x)==1) 0
                   else seq(-length(x)/2,length(x)/2,length=length(x))))

最终情节如下所示:

library(ggplot2)
ggplot( dat,aes(x=factor(group),y=difference) ) +
  geom_bar( width=.75,aes(fill=as.factor(Mutation)),stat="identity",
            position=position_dodge(height=0.9)) +
  geom_text(aes(label=Mutation, vjust = group_adjust,y=0),angle=90)+
  theme_bw() + 
  theme(legend.position="none") +
  ylim(extendrange(dat$difference))

在此处输入图像描述

于 2013-06-20T22:55:46.817 回答
1

我仍然觉得我刚刚开始学习使用 ggplot2 但也许你可以将我所做的调整到一个看起来更接近你想要的情节。如果任何更有经验的人可以指导我以更好的编码方式解决这个问题,我将不胜感激。

n_in_group <- summary(as.factor(dat$group))
group_adjust <- c()
for(i in seq(n_in_group)) { 
  if(n_in_group[i] == 1)   {group_adjust <- c(group_adjust,0)         }
  if(n_in_group[i] == 2)   {group_adjust <- c(group_adjust,-1,1)  }
  if(n_in_group[i] == 3)   {group_adjust <- c(group_adjust,-1,0,1)}
}
library(ggplot2)
ggplot( dat,aes(x=factor(group),y=difference) ) +
  geom_bar( width=.75,aes(fill=as.factor(Mutation)),stat="identity",
            position="dodge") +
  geom_text(aes(label=Mutation, vjust = group_adjust),angle=90)+
  theme_bw() + 
  theme(legend.position="none")
于 2013-06-20T20:57:30.297 回答