I am trying to build a complex barcher using geom_bar and mark each category with its own value within barchart. Since some categories have small values, the height of the corresponding segment of velvet is sometimes small. So, I'm trying to adjust the size of labels using geom_text .
I tried to define a vector called size , which changes depending on the value of the variable that I am trying to build, but although the size of the labels varies between categories, it does not seem to be related to the values.In addition, I'm not sure why I get the legend for my label size on the right side of the graph.
Here is a split version of the code I'm using:
library(ggplot2) library(plyr) library(scales) Var1 = as.factor(rep(c("A", "B", "C", "D", "E", "F"),2)) Var2 = as.factor(rep(c("Y1","Y2"),each=6)) Freq = c(0.4, 0.1, 0.3, 0.1, 0.05, 0.05,0.2,0.2,0.3,0.2,0.05,0.05) Data = data.frame(Var1, Var2, Freq) Data <- ddply(Data, .(Var2), mutate, y = cumsum(Freq)-Freq/2) size = ifelse(Data$Freq > 0.05, 10, 3) label = paste(round(Data$Freq*100,0),"%", sep = "") p = ggplot(data = Data, aes(x = factor(''), y = Freq, fill = Var1)) + geom_bar(stat = "identity",position = "fill", width = 1) + scale_fill_brewer(palette = 3) + facet_grid(facets = . ~ Var2) + geom_text(aes(y = y, label = label, position ="identity", face = "bold"), size = size, 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")) p
As far as I can see, the problem is caused by faces, as this slightly simplified version (i.e. without faces) works fine:
library(ggplot2) library(plyr) library(scales) Var1 = as.factor(c("A", "B", "C", "D", "E", "F")) Freq = c(0.4, 0.1, 0.3, 0.1, 0.05, 0.05) y = cumsum(Freq)-Freq/2 Data = data.frame(Var1, Freq, y) size = ifelse(Data$Freq > 0.05, 10, 3) label = paste(round(Data$Freq*100,0),"%", sep = "") p = ggplot(data = Data, aes(x = factor(''), y = Freq, fill = Var1)) + geom_bar(stat = "identity",position = "fill", width = 1) + scale_fill_brewer(palette = 3) + geom_text(aes(y = y, label = label, position ="identity", face = "bold"), size = size, 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")) p