为 ggplot2 中的变量设置/Link 点和形状选项

Set / Link point and shape options for variables in ggplot2

我想 link 我在数据框中的变量,即 ('prop1', 'prop2', 'prop3') 到图中的特定颜色和形状。但是,我还想排除数据(使用 dplyr::filter)以自定义绘图显示,而不更改用于特定变量的点和形状。下面给出了一个最小的例子。

  library(ggplot2)
  library(dplyr)
  library(magrittr)

obj <- c("cmpd 1","cmpd 1","cmpd 1","cmpd 2","cmpd 2")
  x <- c(1, 2, 4, 7, 3)
  var <- c("prop1","prop2","prop3","prop2","prop3")
  y <- c(1, 2, 3, 2.5, 4)
  col <- c("#E69F00","#9E0142","#56B4E9","#9E0142","#56B4E9")
  shp <- c(0,1,2,1,2)
  df2 <- cbind.data.frame(obj,x,var,y,col,shp)

  plot <- ggplot(data = df2 %>%
                       filter(obj %in% c(
                         "cmpd 1",
                         "cmpd 2"
                       )),
                     aes(x = x,
                         y = y,
                         colour = as.factor(var), 
                         shape = as.factor(var))) +  
    geom_point(size=2) + 
    #scale_shape_manual(values=shp) +
    #scale_color_manual(values=col) + 
    facet_grid(.~obj) 
  plot

但是,当我编辑 cmpd1(只是在代码中散列)时,prop2prop3 的颜色和形状因 cmpd2 发生变化(请参见图 2)。

为此,我尝试将 scale_shape_manualscale_color_manual 添加到代码(当前已散列)中,并将它们 link 编辑到特定的变量(colshp) 在数据框 (df2) 中,但同样的问题是当排除其中一个条件时,这些变量的形状和颜色都会发生变化?

感谢任何帮助。

尝试这样的事情:

library(tidyverse)
obj <- c("cmpd 1","cmpd 1","cmpd 1","cmpd 2","cmpd 2")
x <- c(1, 2, 4, 7, 3)
var <- c("prop1","prop2","prop3","prop2","prop3")
y <- c(1, 2, 3, 2.5, 4)

df2 <- cbind.data.frame(obj,x,var,y)
col <- c("prop1" = "#E69F00", 
         "prop2" = "#9E0142",
         "prop3" = "#56B4E9")
shp <- c("prop1" = 0, 
         "prop2" = 1,
         "prop3" = 2)

plot <- ggplot(data = df2 %>%
                 filter(obj %in% c(
                   "cmpd 1",
                   "cmpd 2"
                 )),
               aes(x = x,
                   y = y,
                   colour = var, 
                   shape = var)) +  
  geom_point(size=2) + 
  scale_shape_manual(values=shp) +
  scale_color_manual(values=col) + 
  facet_grid(.~obj) 
plot