geom_bar中的标签错误 [英] Label error in geom_bar
本文介绍了geom_bar中的标签错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将标签放在 geom_bar
中,但我不能。
I'm trying put label in geom_bar
but I can't.
我的代码
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)
推荐答案
通过使用 plyr
pacakage中的 ddply
,我们可以创建一个基于累积为每个标签获得正确的位置:
By using ddply
from the plyr
pacakage, we can create a new variable based on the cumulative sums to get the correct position for each label:
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中心在该段的中间。
This creates a new variable of the cumulative sum by group, and then subtracts the frequency itself divided by 2 to center it in the middle of that segment.
这篇关于geom_bar中的标签错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文