r创建颜色栏,将yaxis标记为组

r创建颜色栏,将yaxis标记为组,r,ggplot2,colors,axis,R,Ggplot2,Colors,Axis,我正在绘制热图,并希望按组以颜色标记yaxis: 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") %>

我正在绘制热图,并希望按组以颜色标记yaxis:

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))
有没有办法做到这一点


这个例子和代码的功劳归于[

您可以单独构建一个条,并用它注释您的图形

e、 g

输出如下


@但是要小心,我在创建带有大正方形点的条形图时有点作弊。因此,你可以有不连续的组,但点之间的重叠可能会使它们随着热图的中断而略微偏移。是的,我意识到条形图与热图组的中断而略微偏移。但我认为这样更好什么都没有。当热图成排增加时,差异变得更加不明显
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