ggplot/ggtern 使用 scale_fill_gradient 手动映射多个梯度

ggplot/ggtern manually mapping multiple gradients with scale_fill_gradient

我正在为我的数据生成热图(下面是数据的摘录),但我想要每个 Color_ID 的不同热图。因此,例如,所有 5 的 Color_ID 都应采用一种比例(粉红色到红色),而所有 4 的 Color_ID 应采用不同的比例(浅橙色到深橙色)。但是,我好像一次只能做一个秤。

ID  x   y   z   Color_ID    TypeID
1   ORA 0.6737  0.2047  0.1217  5   4
2   BAT 0.9333  0.0530  0.0137  5   4
3   HYX 0.5816  0.2797  0.1387  4   5
4   RAB 0.5900  0.3300  0.0800  1   5
5   ROO 0.6583  0.2171  0.1246  1   5
6   HIP 0.6691  0.1945  0.1364  1   5
7   TOR 0.7196  0.1890  0.0914  2   5
8   ELE 0.7637  0.1503  0.0860  3   5
9   PP  0.6446  0.2213  0.1341  5   7
10  BAR 0.7216  0.1934  0.0850  4   7
11  GAT 0.1151  0.5716  0.3133  1   3
12  EAG 0.2932  0.3889  0.3179  1   3
13  SNK 0.3688  0.3126  0.3186  1   3

这是我的代码的主要部分:

Iplot <- ggtern(data = my.data, aes(x=x, y=y, z=z, label = ID)) +
  stat_density2d(method = "lm", fullrange = T,
                 n = 100, geom = "polygon",
                 aes(fill = ..level..,
                     alpha = ..level..))+
  coord_tern(L="x",T="y",R="z") +
  theme_anticlockwise() +
  scale_fill_gradient(low = "#FED9A9",high = "#F08600")  +
  geom_text(color="black", size = 3)+ 
  facet_wrap(~ TypeID, ncol = 2)

Iplot

但是,所有 4 个方面都使用相同的比例。如何为每个 Color_ID 创建单独的比例?我试过类似的东西:

scale_fill_gradient(low = c("#FED9A9","#CDFF99"),high = c("#F08600","#FC4D45")



 scale_fill_gradient(low = "#FED9A9",high = "#F08600", data = subset(my.data, Color_ID == 4) + scale_fill_gradient(low = "#CDFF99",high = "#FC4D45", data = subset(my.data, Color_ID == 3)

谢谢!

图形语法的全部要点(ggplot 和 ggtern 的基础)是以一种不会混淆 reader 的方式进行美学映射,这就是为什么相同的原因映射在构面之间共享。

据我所知,要实现您所寻求的目标,唯一的方法是分别绘制每个方面,然后将它们组合起来。请看下面的代码:

library(ggtern)
my.data <- read.table("~/Desktop/ggtern_sample.txt",header=T) #Edit as required

plots <- list()
for(x in sort(unique(my.data$TypeID))){
  df.sub <- my.data[which(my.data$TypeID == x),]
  scales_gradient = if(x %% 2 == 0){
    scale_fill_gradient(low="green",high = "red") 
  }else if(x == 5){
    scale_fill_gradient(low="#FED9A9",high = "#F08600") 
  }else{
    scale_fill_gradient(low="blue",high = "magenta") 
  }

  #Build the plot for this subset
  base <- ggtern(data = df.sub, aes(x=x, y=y, z=z, label = ID)) +
    stat_density2d(method = "lm", fullrange = T,
                   n = 100, geom = "polygon",
                   aes(fill = ..level..,
                       alpha = ..level..))+
    scale_alpha(guide='none') + 
    coord_tern(L="x",T="y",R="z") +
    theme_anticlockwise() +
    scales_gradient +
    geom_text(color="black", size = 3)+ 
    facet_wrap(~ TypeID, ncol = 2)

  #Add to the list
  plots[[length(plots)+1]] = base
}

#Add to multiplot
ggtern.multi(plotlist = plots,cols=2)

这会产生以下结果: