Two lines for x-axis label with different font sizes in R grouped bar chart

Viewed 237

I have a grouped bar chart where X-axis contains Employee types e.g. Staff, Teacher etc. and I put the label for each group like following enter image description here

I would like to put the numbers below each group inside parenthesis and make the font size smaller. This is what I tried so far

data <- read.csv("Emp.txt", sep = "\t" , header = TRUE)
df1<-tibble(data)
df1<- mutate(df1, emp_class = cut(Age, breaks = c(0, 19, 22, 25, 28, 31, 34, 52, 75), 
                                  labels = c('(0-19)', '(20-22)', '(23-25)', '(26-28)', '(29-31)', '(32-34)', '(35-52)', '(53-75)'))) 

df1 <- df1 %>% 
  group_by(Emp_group) %>% 
  add_count() 

df1 <- mutate(df1, x_axis = paste(Emp_group, n, sep = "\n"))
my_ggp <- ggplot(df1, aes(x=as.factor(x_axis), fill=as.factor(emp_class)))+
  geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]*100), position="dodge") + ylab('% Employes') +xlab("") + labs(fill = "Age group") 
df1
my_ggp + theme(text = element_text(size = 20))  
1 Answers

I'm not aware of a good way to apply different formats to a single axis label text. To get the raw count on a line below the axis label is relatively straightforward, though. For example:

library(ggplot2)
library(dplyr)

dat <- mtcars %>%
    count(cyl, carb) %>%
    mutate(across(c(cyl, carb), ~ as.factor(.))) %>%
    group_by(cyl) %>%
    mutate(total = sum(n))

dat %>%
    ggplot(aes(x = cyl, y = n, fill = carb)) +
        geom_col(position = "dodge") +
        scale_x_discrete(labels = function(cyl) {
            total <- unique(pull(filter(dat, cyl == cyl), total))
            paste0(cyl, "\n (n = ", total, ")")
        })

The idea is to use a function in scale_x_discrete (or whatever scale_x_... type your data is). The function takes in breaks, which in this example would be c(4, 6, 8), and with your data would be c("Custodian", "Staff", "Teacher"). You then use that to find the totals value (I've shown one way, there are lots of alternatives). Finally, you construct your axis label with paste, and use "\n" to specify the new line.

enter image description here

Related