I would like to align the labels for the count and percentage over the columns in a group of bar charts. In some of the charts in the group, not all values are represented. There are three values for sentiments -- positive, neutral, and negative -- but some offices only have one or two of the responses. For the individual charts without a value, the labels don't align. How can I get the columns and labels in alignment.
Here is the data and my code -- really appreciate the support!
data
office sentiment
1 positive
1 positive
1 neutral
1 neutral
1 positive
1 positive
1 positive
1 positive
1 neutral
1 neutral
1 neutral
1 positive
1 positive
1 negative
1 negative
1 positive
1 neutral
1 neutral
1 neutral
1 positive
1 neutral
1 neutral
1 negative
1 positive
1 positive
1 neutral
2 positive
2 positive
2 neutral
3 positive
3 positive
3 positive
3 positive
4 positive
4 negative
4 neutral
5 positive
6 positive
6 positive
6 positive
6 positive
6 neutral
6 positive
6 positive
6 positive
6 positive
7 positive
8 neutral
8 positive
8 positive
df <- [office, sentiment] # a data frame or tibble of the above data set
office_sentiment <- df[ , c("office","sentiment")]
office_sentiment <- office_sentiment %>% group_by(sentiment,office) %>% summarize(count = n())
office_sentiment <- filter(office_sentiment,count >= 1,sentiment != "NA") #%>%
office_sentiment
office_sentiment_percentage <- df[ , c("office","sentiment")]
office_sentiment_percentage <- office_sentiment_percentage %>% group_by(sentiment,office) %>% summarize(count = n())
office_sentiment_percentage <- filter(office_sentiment_percentage,count >= 1,sentiment != "NA") %>%
mutate(percentage=count/sum(count)*100)
office_sentiment_percentage$percentage <- paste0(round(office_sentiment_percentage$percentage,1),"%")
# the function i use for most bar charts
myBarChart_2 <- function(data,var1,var2,count,title,xLabel,yLabel) {
ggplot(data, aes_string(x=var1, y=count, fill=var2)) +
ggtitle(title) +
geom_bar(stat = 'idoffice',width=1,position = position_dodge2(padding=0.1,reverse=FALSE,preserve=c("single"))) +
scale_color_manual(values=c("#66CCFF","#009999","#FF66CC"),aesthetics = c("colour", "fill")) +
scale_y_continuous(sec.axis=waiver(),expand = expansion(mult = c(0,0.05))) +
facet_wrap(var1, strip.position="bottom",scales = "free_x") +
xlab(xLabel) +
ylab(yLabel) +
theme_set(myBar_theme) +[![enter image description here][1]][1]
theme(axis.text.x=element_blank())
}
# code for this sample set of charts
myBarChart_2(office_sentiment_percentage,'officeType','sentiment','count',"Sentiment by Office","sentiment","total") +
(aes(group=factor(sentiment, levels=c('positive','neutral','negative')))) +
geom_text(aes(label = count),vjust=1.5,position=position_dodge2(width=1),size=2.5) +
geom_text(aes(label = percentage),vjust=-.3,position=position_dodge2(width=1),size=2.5) +
guides(fill = guide_legend(reverse = TRUE))