Создайте цветную полосу для обозначения якс в группах - PullRequest
0 голосов
/ 07 января 2020

Я строю тепловую карту и хотел бы обозначить яксис по группам в цветах:

library(ggplot2)
library(tidyr)
library(tibble)
library(hrbrthemes)
library(dplyr)

# Volcano dataset
#volcano

# Heatmap 
df <- volcano %>%

    # Data wrangling
    as_tibble() %>%
    rowid_to_column(var="X") %>%
    gather(key="Y", value="Z", -1) %>%

    # Change Y to numeric
    mutate(Y=as.numeric(gsub("V","",Y))) %>%
    mutate(group=rep(1:3,each=1769))

ggplot(df,aes(X, Y, fill= Z)) + 
    geom_tile() +
    theme(legend.position="none") +
    scale_y_discrete(expand=c(0, 0)) +
    scale_x_continuous(expand = c(0, 0))

enter image description here

Есть ли способ сделать так?

Кредит этого примера и кода идет к [https://www.r-graph-gallery.com/79-levelplot-with-ggplot2.html] [2]

1 Ответ

1 голос
/ 07 января 2020

Вы можете построить «бар» отдельно и комментировать свою фигуру.

Например,

library(ggplot2)
library(reshape2)

groups <- data.frame(samp_id = factor(1:100), group = c(rep('A', 20), rep('B', 50), rep('C', 30)))

dat <- matrix(rnorm(500), nrow = 100)
# make group B distinguishable
dat[groups$group=='B',] <- dat[groups$group=='B',] + 4

hm <- ggplot(melt(dat), aes(fill = value, x = Var2, y = Var1)) + geom_tile() + theme_classic() + 
  theme(axis.title.y = element_blank(), 
        axis.text.x = element_blank())

# Build a legend "bar"
leg <- ggplot(groups, aes(y = samp_id, x = 0)) + geom_point(aes(color = group), shape = 15, size = 3, show.legend = F) + 
  theme_classic() + 
  theme(axis.title = element_blank(), axis.line = element_blank(), 
        axis.text = element_blank(), axis.ticks = element_blank(), 
        plot.margin = unit(c(0,0,0,0), "cm"))

leg

# annotate hm with the bar
hm + annotation_custom(ggplotGrob(leg), 
                       xmin = .2, xmax = .5, 
                       ymin = 0, ymax = 100.5) # n + .5 since tiles are 1 in width centered on the value

выводит следующие значения:

enter image description here

...