user3510503
user3510503

Reputation: 358

Adding data labels to grouped column chart

I'm trying to create a simple grouped column chart with data labels, the problem I'm facing is that the labels are not getting displayed correctly. See the screenshot below:

enter image description here

Another issue here is that after adding the geom_text() statement,I'm getting 2 unwanted items above and below the legend on the far right i.e. size and colour

Data Used

data<-structure(list(survey_period = c("2019_H2", "2020_H1", "2019_H2", 
                                   "2020_H1", "2019_H2", "2020_H1", "2019_H2", "2020_H1", "2019_H2", 
                                   "2020_H1"), subgroup = c("AS", "AS", "BL", "BL", "HI", "HI", 
                                                            "Others", "Others", "WH", "WH"), fav = c(0.639136555607696, 0.83034379671151, 
                                                                                                     0.653710247349823, 0.822349570200573, 0.658051689860835, 0.812018489984592, 
                                                                                                     0.654872749844817, 0.819091796875, 0.624846248462485, 0.795588612464735
                                                            )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
                                                            ))

Code for the plot

library(RColorBrewer)
library(scales)
library(ggplot2)

data %>%
  ggplot( aes(x=survey_period, y=fav, group=subgroup, fill=subgroup, width=.7)) +
  geom_col(colour="black",width=0.5,position=position_dodge(0.8)) +
  ggtitle("Trended Favorability") +
  theme(axis.line=element_line()) +
  ylab("% Favorable") +  
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + # 
  scale_fill_brewer(palette="PuBu") +
  geom_text(aes(label=scales::percent(fav, accuracy=.1), size=3,color="white",fontface = "bold"))

I'd like to know what needs to be changed in this code so that each of the bar gets their own label.

Upvotes: 0

Views: 129

Answers (1)

DPH
DPH

Reputation: 4344

the "fav_text" varibale is missing from the example data - so I used "subgroup":

library(RColorBrewer)
library(scales)
library(ggplot2)

data %>%
  ggplot(aes(x=survey_period, y=fav, group=subgroup, fill=subgroup, width=.7)) +
  geom_col(colour="black",width=0.5,position=position_dodge(0.8)) +
  geom_text(aes(label=subgroup),
            fontface = "bold", 
            vjust = -.5, # play with these to adjust position
            hjust = .5, # play with these to adjust position
            size = 3,
            colour = "black",
            position = position_dodge(0.8)) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + # 
  scale_fill_brewer(palette="PuBu") +
  ggtitle("Trended Favorability") +
  ylab("% Favorable") +  
  theme(axis.line=element_line())

the plot

Upvotes: 1

Related Questions