writer_typer
writer_typer

Reputation: 798

How to display variable and value labels in ggplot bar chart?

I'm trying to get the variable labels and value labels to be displayed on a stacked bar chart.

library(tidyverse)
data <- haven::read_spss("http://staff.bath.ac.uk/pssiw/stats2/SAQ.sav")
data %>% 
  select(Q01:Q04) %>% 
  gather %>% 
  group_by(key, value) %>% 
  tally %>% 
  mutate(n = n/sum(n)*100, round = 1) %>% 
  mutate(n = round(n, 2)) %>% 
  ggplot(aes(x=key, y=n, fill=factor(value))) + 
  geom_col() + 
  geom_text(aes(label=as_factor(n)), position=position_stack(.5)) + 
  coord_flip() +
  theme(aspect.ratio = 1/3) + scale_fill_brewer(palette = "Set2")

enter image description here Instead of Q01, Q02, Q03, Q04, I would like to use the variable labels.

library(labelled)

var_label(data$Q01)
Statistics makes me cry

var_label(data$Q02)
My friends will think Im stupid for not being able to cope with SPSS

var_label(data$Q03)
Standard deviations excite me

var_label(data$Q04)
I dream that . . . 

along with associated value labels

val_labels(data$Q01)

Strongly agree             Agree           Neither          Disagree Strongly disagree      Not answered 
                1                 2                 3                 4                 5                 9 

I tried using label = as_factor(n) but that didn't work.

Upvotes: 2

Views: 1321

Answers (1)

akrun
akrun

Reputation: 887311

We may extract the labels and then do a join

library(forcats)
library(haven)
library(dplyr)
library(tidyr)
library(labelled)
subdat <- data %>% 
   select(Q01:Q04)
d1 <- subdat %>%
    summarise(across(everything(), var_label)) %>%
    pivot_longer(everything())
subdat %>% 
    pivot_longer(everything(), values_to = 'val') %>%
    left_join(d1, by = 'name') %>% 
    mutate(name = value, value = NULL) %>%
    count(name, val) %>% 
    mutate(n = n/sum(n)*100, round = 1) %>% 
    mutate(n = round(n, 2)) %>% 
    ungroup %>%
    mutate(labels = names(val_labels(val)[val])) %>%  
    ggplot(aes(x=name, y=n, fill=labels)) +   
     geom_col() + 
     geom_text(aes(label=as_factor(n)), 
            position=position_stack(.5)) + 
     coord_flip() +
     theme(aspect.ratio = 1/3) + 
     scale_fill_brewer(palette = "Set2")

-output

enter image description here

Upvotes: 3

Related Questions