geom_bar中的标签错误

时间:2014-05-23 14:42:36

标签: r ggplot2 geom-bar

我正在尝试将标签放在geom_bar中,但我不能。

我的代码

df <- data.frame(
 uni = rep(c("D","E","F","G","H"),3),
 Var1 = factor(c(rep("A",5),rep("B",5),rep("C",5))),
 Freq = c(53.6,50.0,48.5,50.0,56.2,23.2,18.5,27.7,20.0,14.3,23.2,31.5,23.8,30.0,29.6))


df$label = paste(round(df$Freq,0),"%", sep = "")
ggplot(data = df, aes(x = uni, y = Freq, fill = Var1)) +
geom_bar(stat = "identity",position = "fill", width = 1) +
scale_fill_brewer(palette = 3) + geom_text(aes(y = Freq, label = label, position ="identity", face = "bold", size = 1), hjust=0.5, vjust=0.5) + 
xlab('') + 
ylab('') + 
labs(fill = '') + 
ggtitle('Example') + 
theme(axis.text.y = element_text(size=14,face="bold"), panel.background = element_blank(), plot.title = element_text(size = 20, colour = "black", face = "bold")) + 
guides(size=FALSE)

return this

1 个答案:

答案 0 :(得分:1)

通过使用ddply pacakage中的plyr,我们可以根据累积总和创建一个新变量,以获得每个标签的正确位置:

library(plyr)
df <- data.frame(
    uni = rep(c("D","E","F","G","H"),3),
    Var1 = factor(c(rep("A",5),rep("B",5),rep("C",5))),
    Freq = c(53.6,50.0,48.5,50.0,56.2,23.2,18.5,27.7,20.0,14.3,23.2,31.5,23.8,30.0,29.6))

df = ddply(df, .(uni), transform, labPosition = cumsum(Freq)-Freq/2)

df$label = paste(round(df$Freq,0),"%", sep = "")
ggplot(data = df, aes(x = uni, y = Freq, fill = Var1)) +
    geom_bar(stat = "identity", width = 1) +
    scale_fill_brewer(palette = 3) + 
    geom_text(aes(y = labPosition, label = label, position ="identity"), hjust=0.5, vjust=0.5, size = 1, face = "bold") + 
    xlab('') + 
    ylab('') + 
    labs(fill = '') + 
    ggtitle('Example') + 
    theme(axis.text.y = element_text(size=14,face="bold"), panel.background = element_blank(), plot.title = element_text(size = 20, colour = "black", face = "bold")) + 
    guides(size=FALSE)

这将按组创建累积和的新变量,然后减去频率本身除以2,使其居中于该段的中间。

enter image description here