0

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

我在整个水柱中进行了测量,其平均值已计算为 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))

在此处输入图像描述

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

为了提供一个可重复的示例,我使用了 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))

哪个生产

在此处输入图像描述

有没有办法可以为绘图上的每个变量添加比例尺?

这个问题与其他问题相似(例如,这里这里),但它们不使用 x 轴上的分类变量,因此我无法修改它们以生成所需的图。

这是我想到的仅使用四个变量的情节模型,除了我将使用情节底部的所有图例水平放置theme(legend.position="bottom")

在此处输入图像描述

4

1 回答 1

0

希望这会有所帮助:函数 myfun 最初由 Duck 在这里发布:R ggplot heatmap with multiple rows have 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)

在此处输入图像描述

于 2021-01-28T16:16:32.133 回答