Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot insert line between factor levels

Tags:

r

ggplot2

factors

I am making a tilemap in ggplot as below. 2 questions:

1) How can I expand the x-axis limits to label my groups at x = 4? 2) How can I put horizontal lines between Groups (i.e. a line between 1 and 2, 2 and 3, etc.) automatically, not specifying y-value manually?

require(tidyverse)
set.seed(1)
df <- data.frame(ID = as.character(c(1:50)),
                 Group = sample(1:8, 50, replace = T),
                 var1 = sample(c('Y', 'N'), 50, replace = T),
                 var2 = sample(c('Y', 'N'), 50, replace = T),
                 var3 = sample(c('Y', 'N'), 50, replace = T)) %>% 
  gather('var', 'y_n', var1:var3) %>% 
  arrange(-Group) %>% 
  mutate(ID = factor(ID, levels = unique(ID, ordered = T)))

ggplot(df, aes(var, ID, label = Group))+
  geom_tile(aes(fill = y_n), color = 'white')+
  scale_fill_manual(values = c('white', 'lightblue'))+
  scale_x_discrete(expand = c(0, 0))+
  geom_text(x = 3.5, hjust = 'right')

enter image description here

like image 631
user42485 Avatar asked Jul 24 '26 11:07

user42485


1 Answers

Using facets solves both your problems: if you facet by Group you can edit the facet panel to specify a black border around each group, and it will automatically label each group outside the plot area.

ggplot(df, aes(var, ID, label = Group)) +
  geom_tile(aes(fill = y_n), color = 'white') +
  scale_fill_manual(values = c('white', 'lightblue')) +
  scale_x_discrete(expand = c(0, 0)) +
  facet_grid(Group~., scales = "free", space = "free") + #facet by group
  theme(strip.background = element_blank(), #remove background for facet labels
        panel.border = element_rect(colour = "black", fill = NA), #add black border
        panel.spacing = unit(0, "lines")) #remove space between facets

Within facet_grid(), It's important to add scales = "free" so each facet has only the y values present for that group, and add space = free so the size of each group is adjusted based on how many y-values it has.

enter image description here

like image 131
Jan Boyer Avatar answered Jul 27 '26 08:07

Jan Boyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!