For the following plot, I want to color the points according to the label, whereby all labels that contain "1" are red in their string, labels that contain "2" in their string are blue and labels that contain "3" in their string are green.
I'm not sure what the best approach is to achieve this.
label <- c("A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3")
val <- sample(1:100, 9, replace=FALSE)
d <- data.frame(label, val)
ggplot(d, aes(x=val,y=label)) geom_point()
CodePudding user response:
You can achieve that creating a variable with the categories and ploting them in the colour
parameter.. Like this:
d <- data.frame(label, val) %>%
mutate(category = substr(label, 2,2))
ggplot(d, aes(x=val,y=label))
geom_point(aes(colour = category), size = 15)
scale_color_manual(values = c("red","blue","green"))
CodePudding user response:
You'll need to create some categorical variables defining "1", "2" and "3" either in your d
dataframe, or in ggplot
directly.
library(tidyverse)
label <- c("A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3")
val <- sample(1:100, 9, replace=FALSE)
d <- data.frame(label, val)
ggplot(d, aes(x = val,
y = label,
col = case_when(grepl("1", label) ~ "1",
grepl("2", label) ~ "2",
grepl("3", label) ~ "3")))
geom_point()
scale_color_manual(name = "Color",
values = c("1" = "red", "2" = "blue", "3" = "green"))
Created on 2022-05-19 by the reprex package (v2.0.1)