I would like to link variables I have in a dataframe i.e. ('prop1', 'prop2', 'prop3'
) to specific colours and shapes in the plot. However, I also want to exclude data (using dplyr::filter
) to customise the plot display WITHOUT changing the points and shapes used for a specific variable. A minimal example is given below.
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
However, when I redact cmpd1
(just hashing in code) the colour and shape of prop2
and prop3
for cmpd2
change (please see plot2).
To this end, I tried adding in scale_shape_manual
and scale_color_manual
to the code (currently hashed) and linked these to specific vars (col
and shp
) in the dataframe (df2
), but the same problem arises that both the shape and color of these variables changes when excluding one of the conditions?
Any and all help appreciated.
CodePudding user response:
Try something like this:
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