d.b
d.b

Reputation: 32548

grouping labels in ggplot

Here's my attempt to create a heatmap using ggplot2.

#DATA
set.seed(42)
df1 = data.frame(ID = paste0("I", 1:40),
                 group = rep(c("Dry", "Rain"), each = 20),
                 subgroup = rep(paste0("S", 1:4), each = 10),
                 setNames(data.frame(replicate(8, rnorm(40))), letters[1:8]))
library(reshape2)
df1 = melt(df1, id.vars = c("ID", "group", "subgroup"))
df1 = df1[order(df1$group, df1$subgroup),]
df1$fact = paste(df1$subgroup, df1$ID)
df1$fact = factor(df1$fact, levels = unique(df1$fact))

#PLOT
library(ggplot2)
ggplot(df1, aes(x = variable, y = fact, fill = value)) +
    geom_tile() +
    scale_y_discrete(labels = df1$subgroup[!duplicated(df1$ID)])

The plot is exactly what I want except for the fact that the labels S1, S2, S3, and S4 repeat 10 times each. Is there a way to display them only one time and then put some kind of break between S1, S2, S3, and S4.

enter image description here

I am also curious if there is way to put group to the left of subgroup in the plot as a secondary y-axis but that is optional.

Upvotes: 2

Views: 2753

Answers (1)

Djork
Djork

Reputation: 3369

You can use facet_grid which would address both having a subgroup indicator on the y-axis and a white space separation between the subgroups.

You can also remove y-axis labels in theme to avoid redundancy.

ggplot(df1, aes(x = variable, y = fact, fill = value)) +
  geom_tile() +
  facet_grid(subgroup~., scales="free_y") +
  theme(axis.text.y = element_blank())

Note: scales="free_y" is necessary because fact is not identical across subgroups, see output if this parameter is absent.

enter image description here

Upvotes: 1

Related Questions