简体   繁体   中英

Adding a Group Label to x-axis in geom_tile()

I'm looking to add an overarching grouping label to variables on the x-axis of geom_tile().

This is similar to the result I'm looking for: 在此处输入图像描述

However, the best I can come up with (WITHOUT using geom_text() and manually adding group 1, group 2 and group 3 above the x-axis variables) is this, which just creates a new variable containing both pieces on information:

set.seed(1)
df <- expand.grid(group = c("Group 1", "Group 2", "Group 3"), 
                  xVar = c("A", "B"), 
                  yVar = c("x","y","z")) %>% 
  mutate(fillValue = factor(sample(c(0,1), 18, TRUE))) %>%
  mutate(group_and_xVar = paste(group, xVar, sep = "\n"))


ggplot(df, aes(x = group_and_xVar, y = yVar, fill = fillValue))+
  geom_tile(colour = "black") +
  scale_x_discrete(position = "top", expand = c(0,0))+
  scale_y_discrete(expand = c(0,0))+
  scale_fill_manual(values=c("#FF4933", "#72AF4A"))+
  labs(x = "", y = "", fill = "")+
  theme_bw()+
  theme(axis.text.x = element_text(angle = 0, vjust = .05),
        legend.position = "none")

在此处输入图像描述

This is not what I want. I'd like to have each group only appear once on the plot and for the code to be soft coded (adaptable to new data or groups that might be added in the future). I've also attempted using facet_grid/facet_wrap but I haven't had luck with those.

Also adjusting the height of the cells to look more like the first image would be a bonus:)

A solution inspired by this post :

ggplot(df, aes(x = xVar, y = yVar, fill = fillValue)) +
    geom_tile(colour = "black") +
    scale_x_discrete(position = "top", expand = c(0,0)) +
    scale_y_discrete(expand = c(0,0)) +
    labs(x = "", y = "", fill = "") +
    facet_grid(~group) +
    coord_fixed(ratio=0.5) +
    theme(legend.position = "none",
          panel.spacing = unit(0, "lines"), 
          strip.background = element_blank(),
          strip.placement = "outside")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM