r创建颜色条以将yaxis标记为组 [英] r Create color bar to label yaxis into groups
本文介绍了r创建颜色条以将yaxis标记为组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在绘制一个热图,并希望按颜色在组中标记yaxis:
库(ggplot2)图书馆(tidyr)图书馆(小标题)图书馆(hrbrthemes)图书馆(dplyr)#火山数据集#火山#热图df<-火山%&%;%#数据纠缠as_tibble()%>%rowid_to_column(var ="X")%>%collect(key ="Y",value ="Z",-1)%>%#将Y更改为数字mutate(Y = as.numeric(gsub("V",",Y)))%>%mutate(group = rep(1:3,each = 1769))ggplot(df,aes(X,Y,fill = Z))+geom_tile()+主题(legend.position ="none")+scale_y_discrete(expand = c(0,0))+scale_x_continuous(expand = c(0,0))
有办法吗?
此示例和代码的信用转到[
I am plotting a heatmap and would like to label the yaxis by group in colors:
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))
Is there a way to do so?
Credit of this example and code goes to [https://www.r-graph-gallery.com/79-levelplot-with-ggplot2.html][2]
解决方案
You could build a "bar" separately and annotate your figure with it.
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
outputs the following
这篇关于r创建颜色条以将yaxis标记为组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文