2016-06-10 29 views
0

我试图调整我的聚集条形图中每个栏的百分比频率。现在,我的表是这样的:如何在ggplot2中对齐集群条形图上的文本?

Rplot01

下面的代码,以及:

ggplot(graph_data, aes(x, Freq)) + 
    geom_bar(aes(fill = Pref), position = 'dodge', stat = 'identity') + 
    geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))), 
       hjust = -0.25) + 
    labs(list(x = attr(graph_data, 'seg_label'), 
       y = 'Frequency', 
       title = paste('Q:', attr(graph_data, 'question')))) + 
    scale_y_continuous(limits = c(0, 1.2 * max(graph_data$Freq))) + 
    guides(fill = F) + 
    coord_flip() + 
    annotate("text", x = Inf, y = Inf, 
      label = paste0("N = ", sum(graph_data$Freq)), 
      hjust = 1.5, vjust = 1.5) 

我认为这个问题可以在此代码片段来解决,但我不知道如何:

geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))), hjust = -0.25) 

任何帮助将不胜感激!

编辑:这是我的数据的结构的样品,以及:

df <- data.frame(x = rep(c('1824', '2534', '3544'), 3), 
       Pref = rep(c('low', 'neutral', 'high')), 
       Freq = 1:9 * 10) 
+2

的可能的复制[位置GEOM上回避barplot \ _text(http://stackoverflow.com/questions/6017460/position-geom-text-on-dodged-barplot) – aosmith

+0

感谢您的回复。我认为这篇文章的功能贬值 - 我无法用我尝试过的任何示例重新创建它。这篇文章大约5岁,所以如果我没有犯错,我认为这是一个可能的解释。 – nev

+0

修正了它!审美参数'fill'没有被传递到geom_text函数中。我在最初的ggplot声明中包含了所有我的美学,以便修复它,就像这个'ggplot(graph_data,aes(x = x,y = Freq,fill = Pref)' – nev

回答

0

正如在评论中提到的,我认为这是Position geom_text on dodged barplot重复。

但我现在做了,所以我会包含代码。

ggplot(df, aes(x, Freq, fill = Pref)) + 
    geom_bar(position = 'dodge', stat = 'identity') + 
    geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))), 
      position = position_dodge(width = 0.9), hjust = -0.25) + 
    labs(list(x = attr(df, 'seg_label'), 
       y = 'Frequency', 
       title = paste('Q:', attr(df, 'question')))) + 
    scale_y_continuous(limits = c(0, 1.2 * max(df$Freq))) + 
    guides(fill = F) + 
    coord_flip() 

你需要把fillaes所以说geom_text知道哪些由量标签躲闪。

enter image description here