Home > Back-end >  How to specify color and order of color for geom_point()
How to specify color and order of color for geom_point()

Time:08-30

I have looked into the possible solution, but I am hitting a roadblock constantly! Here is the sample data

S <- c("A", "B", "C", "D", "E","F", "G", "H", "I", "J")
x <- c(-2.5, -7, -1, 0, 2.3, 3.1, 5.2, 4.1, -6.3, 2.1)
y <- c(-1, -3, -1, 1, 1, 2, 3, 3, -3, 1)
z <- c("Poor", "Bad", "Poor", "Okay", "Okay", "Good", "Good", "Good", "Bad", "Okay")

df <-data.frame(S, x, y, z)

df %>% 
  ggplot(aes(y, x)) 
  geom_point(aes(color = `z`,
                 size= NULL,)) 
  geom_smooth(method = lm,
              se= F) 
  labs(x = "Coded Value",
       y = "Percent", 
       title = "Effects of Change") 
  theme_minimal()

This produces a graph like the following enter image description here

Now I would like to specify colors for z and get it arranged in the order of Good, Okay, Poor, and Bad and not the random ones in the legend.

I have checked a similar enter image description here

CodePudding user response:

Another option is to just use scale_color_manual, where you would make the call outside of geom_point:

library(tidyverse)

df %>% 
  ggplot(aes(y, x)) 
  geom_point(aes(color = `z`,
                 size= NULL,)) 
  geom_smooth(method = lm,
              se= F) 
  labs(x = "Coded Value",
       y = "Percent", 
       title = "Effects of Change") 
  theme_minimal()  
  scale_color_manual(values=c("green", "blue", "black", "red"),breaks = c("Good", "Okay", "Poor", "Bad"))

enter image description here

  • Related