传递给geom_text的字符串不会闪避

时间:2014-09-04 10:51:22

标签: r ggplot2

我有一些数据:

my_data = data.frame(Grade = rep(c("U", "B", "S", "E"), 3), 
Locality = rep(c("London", "Kent", "Dover"), 4), 
Freq = c(0,0,46,31,0,2,41,28,0,1,21,41), 
n = c(77,77,77,77,71,71,71,71,63,63,63,63), 
Percentage = c(0,0,59.74,40.26,0,2.82,57.75,39.44,0,1.59,33.33,65.08))

我想使用ggplot2绘制此图并将百分比添加为条形图上方的文本。我目前的功能看起来像这样(为了演示的目的,我一直保持简洁):

my_fn = function(data, x, y, z_group, bar_text = T){
p = ggplot(data, aes_string(x = x, y = y))
p = p + geom_bar(aes_string(fill = z_group), position = "dodge", stat = "identity", colour = "black")
if (bar_text == T){
labs = replace(data[[y]], data[[y]] == 0, "")
p = p + geom_text(aes_string(label = labs, x = x, y = y), position = position_dodge(width = 0.9), vjust = -0.5)
}
plot(p)
}

my_fn(my_data, x = "Grade", y = "Percentage", z_group = "Locality")

我遇到的问题是它将labs信息全部放在中间栏上,它只包含第一个非零值。

Imgur

编辑:我发现使用label = deparse(labs)会使用所有标签。

1 个答案:

答案 0 :(得分:2)

这是固定代码;我添加了group美学,labs应作为列包含在数据框中:

my_fn <- function(data, x, y, z_group, bar_text=TRUE) {

  data$labs <- replace(data[[y]], data[[y]] == 0, "")
  p <- ggplot(data, aes_string(x=x, y=y, group=z_group))
  p <- p + geom_bar(aes_string(fill=z_group), position="dodge",
                    stat="identity", colour="black")

  if (bar_text == TRUE) {
    p <- p + geom_text(aes_string(label="labs"),
                       position=position_dodge(width=0.9), vjust=-0.5)
  }
  plot(p)
}

my_fn(my_data, x="Grade", y="Percentage", z_group="Locality")

plot