How do I create x-axis labels from two categorical variables in ggplot2?

Viewed 682

I would like to visualize the following dataset in ggplot2:

   WORD       CATEGORY             n  sum    gloss
   <fct>       <fct>           <int>  <int>  <fct>
 1 A            X                  4  4      'do'
 2 B            X                  3  3      'make'
 3 C            X                  6  9      'wash'
 4 C            Y                  3  9      'wash'    
 5 D            X                  2  2      'walk'
 6 E            X                  2  2      'sing'
 7 F            Y                  2  2      'dance'

On the y-axis I would like to plot the values of n. On the x-axis I would like to plot WORD, but I would also like the gloss associated with each word to appear on a line just beneath the value of the word (i.e., as though there were a carriage return). How do I plot the information from both variables on the x-axis in ggplot2?

2 Answers

You can also try with facet_wrap():

library(ggplot2)
library(dplyr)
#Code
df %>% mutate(gloss=factor(gloss,levels = unique(gloss),ordered = T)) %>%
  ggplot(aes(x=WORD,y=n,group=gloss))+
  geom_point()+
  facet_wrap(.~gloss,scales = 'free_x',nrow = 1,strip.position = 'bottom')+
  theme(strip.placement = 'outside',strip.background = element_blank())

Output:

enter image description here

Or using interaction():

#Code 2
df %>% mutate(gloss=factor(gloss,levels = unique(gloss),ordered = T)) %>%
  ggplot(aes(x=interaction(WORD,gloss,sep = '\n'),y=n,group=gloss))+
  geom_point()+
  xlab('WORD')

Output:

enter image description here

Some data used:

#Data
df <- structure(list(WORD = c("A", "B", "C", "C", "D", "E", "F"), CATEGORY = c("X", 
"X", "X", "Y", "X", "X", "Y"), n = c(4L, 3L, 6L, 3L, 2L, 2L, 
2L), sum = c(4L, 3L, 9L, 9L, 2L, 2L, 2L), gloss = c("'do'", "'make'", 
"'wash'", "'wash'", "'walk'", "'sing'", "'dance'")), row.names = c(NA, 
-7L), class = "data.frame")

Update: This code can order the data:

#Code 3
df %>% mutate(gloss=factor(gloss,levels = unique(gloss),ordered = T)) %>%
  ggplot(aes(x=reorder(interaction(WORD,gloss,sep = '\n'),-n),y=n,group=gloss))+
  geom_point()+
  xlab('WORD')

You can specify that in the labels argument of scale_x_discrete(). We just need a paste() to assemble the columns together.

ggplot(df) +
  geom_point(aes(x = WORD, y = n)) +
  scale_x_discrete(labels = paste(df$WORD, df$gloss, sep="\n"))
Related