I am trying to plot a stacked barchart using geom_bar
and label each category with its value within the barchart. Because some categories have small values, the height of the corresponding segment of the barchart is sometimes small. So, I am trying to adjust the size of the labels using geom_text
.
I have tried to define a vector, called size
, that varies according to the value of the variable I am trying to plot but,although the size of the labels does vary between categories, it does not seem to be related to the values. Also, I am not sure why I am getting a legend for my label size on the right-hand side of the graph.
Here is a stripped version of the code I am 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 issue is caused by the facets since this slightly simplified version (i.e. without the facets) 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
incompatible lengths
withsize
,hjust
etc? – Wackersize
is the same as that ofy
andlabel
. – Behn