如何为 geom_tile 中的每个变量添加单独的图例?

问题描述

我想为每个变量设置一个单独的比例尺。

我在整个水柱中进行了测量,其平均值已计算到 50 厘米的箱中。我想使用 geom_tile 来显示整个水柱中每个 bin 中每个变量的变化,因此该图在 x 轴上有变量(分类),在 y 轴上有深度,每个变量都有不同的色标表示值的变量。我可以使用

一个变量执行此操作
ggplot(data,aes(x=var,y=depth,fill=value,color=value)) + 
        geom_tile(size=0.6)+ theme_classic()+scale_y_continuous(limits = c(0,11),expand = c(0,0))

enter image description here

但是,如果我将所有变量放在一个图上,图例将缩放到所有值的最小值和最大值,因此 bin 之间的变化会丢失。

为了提供一个可重复的示例,我使用了 mtcars,并且包含了 alpha =,当然,这并没有太大帮助,因为每个变量的比例是如此不同

data("mtcars")
# STACKS DATA 
library(reshape2)
dat2b <- melt(mtcars,id.vars=1:2)
dat2b
ggplot(dat2b) + 
  geom_tile(aes(x=variable,y=cyl,fill=variable,alpha = value))

产生什么

enter image description here

有没有办法为图中的每个变量添加比例尺?

这个问题与其他问题类似(例如 herehere),但它们在 x 轴上不使用分类变量,因此我无法修改它们以生成想要的情节。

这是我只使用四个变量的图的模型,除了我会使用 theme(legend.position="bottom")

在图的底部水平放置所有图例

enter image description here

解决方法

希望这有助于: 函数 myfun 最初由 Duck 在这里发布:R ggplot heatmap with multiple rows having separate legends on the same graph

library(purrr)
library(ggplot2)
library(patchwork)
data("mtcars")
# STACKS DATA 
library(reshape2)
dat2b <- melt(mtcars,id.vars=1:2)
dat2b

#Split into list
List <- split(dat2b,dat2b$variable)
#Function for plots
myfun <- function(x)
{
  G <- ggplot(x,aes(x=variable,y=cyl,fill = value)) + 
    geom_tile() + 
  theme(legend.direction = "vertical",legend.position="bottom")
  return(G)
}
#Apply
List2 <- lapply(List,myfun)
#Plot
reduce(List2,`+`)+plot_annotation(title = 'My plot')

patchwork::wrap_plots(List2)

enter image description here