如何在R中沿着ggplot的轴添加自定义着色器? [英] How to add a custom colorer along the axis of a ggplot in R?
问题描述
我想在R中的ggplot热图的轴上创建一个附加条.例如,如果我有一个看起来像这样的数据框:
df<-data.frame(a = c(1,1,1,2,2,2,3,3,3),b = c(1,2,3,1,2,3,1,2,3),y = c(-10,3,5,-2,9,1,-5,-2,0))df [c('a','b')]<-地图(paste0,c('a','b'),df [c('a','b')])dfba1 b1 -10a1 b2 3a1 b3 5a2 b1 -2a2 b2 9a2 b3 1a3 b1 -5a3 b2 -2a3 b3 0
然后我像这样创建一个热图:
gp<-ggplot(dfTest,aes(a,b))+geom_tile(aes(fill = y))gp
产生图:
但是我想在代表其他值的轴周围添加彩色条,例如 z
:
z<-c(2,4,1,7,7,9,3)
其中, z
中的每个条目都代表 df
中的每个条目...即:
a1 = 2,a2 = 4,a3 = 1 ... b1 = 7,b2 = 9,b3 = 3
例如,生成的图看起来像这样的模型:
我正在考虑使用 annotate
,就像在
I want to create an additional bar along the axis of a ggplot heatmap in R. For example, if I have a data frame that looks like this:
df <- data.frame(
a = c(1,1,1,2,2,2,3,3,3),
b = c(1,2,3,1,2,3,1,2,3),
y = c(-10, 3, 5, -2, 9, 1, -5, -2, 0)
)
df[c('a', 'b')] <- Map(paste0, c('a', 'b'), df[c('a', 'b')])
df
a b y
a1 b1 -10
a1 b2 3
a1 b3 5
a2 b1 -2
a2 b2 9
a2 b3 1
a3 b1 -5
a3 b2 -2
a3 b3 0
And I create a heatmap like so:
gp <- ggplot(dfTest, aes(a, b)) +
geom_tile(aes(fill = y))
gp
That produces the plot:
But I want to add a coloured bar around the axis that represents some other value, say z
:
z <- c(2, 4, 1, 7, 9, 3)
where, each entry in z
would represent each entry in df
... that is:
a1 = 2, a2 = 4, a3 = 1 ... b1 = 7, b2 = 9, b3 = 3
For example, the resulting plot would look like this mock-up:
I was thinking of using annotate
like in the example found here... but I cant seem to get it to work for me... any suggestions?
This solution isn't quite there but might get you close.
- I think you'll want to use
ggnewscale
to use two different fill scales in one plot. - There's probably a better function for getting the marginal fills -- I'm manually plopping them in there but the y axis one isn't quite aligned right.
- I'm not sure about the best way to make sure the two marginal plots use the same scale.
First, data:
df <- data.frame(
a = paste0("a", c(1,1,1,2,2,2,3,3,3)),
b = paste0("b", c(1,2,3,1,2,3,1,2,3)),
c = c(-10, 3, 5, -2, 9, 1, -5, -2, 0)
)
z <- c(2, 4, 1, 7, 9, 3)
Then here we plot the tiles as you did, then use ggnewscale::new_scale_fill
to initiate a new scale for the marginal plots.
library(tidyverse)
library(ggnewscale)
ggplot(df) +
geom_tile(aes(a, b, fill = c)) +
scale_fill_continuous(guide = guide_legend(order = 1)) +
# everything after this will have new scale for fill
new_scale_fill() +
geom_tile(data = tibble(a = paste0("a", 1:3),
d = z[1:3]),
aes(x = a, y = 0.5, fill = d, height = 0.1)) +
geom_tile(data = tibble(b = paste0("b", 1:3),
d = z[4:6]),
aes(x = 0.45, y = b, fill = d, width = 0.1)) +
scale_fill_viridis_c(option = "D",
guide = guide_legend(order = 2))
这篇关于如何在R中沿着ggplot的轴添加自定义着色器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!