Draw only specific axis text labels

Viewed 45

I have the following data.table:

require(data.table)
require(ggplot2)

set.seed(1234)
dt = data.table(id = paste0('ID_', 1:2000),
                group = rep(LETTERS[1:5], 400),
                value = as.logical(rbinom(2000, 1, prob = 0.25)))

I would like to create a ggplot like below, where on the y-axis only the text labels, for which the variable value equals TRUE are drawn, without removing the other data. Additionally, it would be best, if the text labels won't overlap (if possible), hence using all the empty y-axis space.

# draws all categorical id values
ggplot(dt, aes(y = reorder(id, -value), x = group, fill = value)) +
  geom_tile() +
  theme_bw()
1 Answers

Update: For the first 100 cases:

dt1 <- dt %>% 
  mutate(ylabel = ifelse(value==TRUE, id, "")) %>% 
  slice(1:100)

ggplot(dt1, aes(y = reorder(id, -value), x = group, fill = value)) +
  geom_tile() +
  scale_y_discrete(
    labels = dt1$ylabel
  ) +
  theme_bw()

enter image description here

Related