Home > Software engineering >  creating a scatter plot using ggplot2 in r
creating a scatter plot using ggplot2 in r

Time:11-25

class_day <- c(1:10)  
control_group <- c(67,72,69,81,73,66,71,72,77,71) 
A_treatment_group <- c(NA,72,77,81,73,85,69,73,74,77)
B_treatment_group <- c(NA,66,68,69,67,72,73,75,79,77) 
class.df<-data.frame(class_day, control_group, A_treatment_group, B_treatment_group)

I tried to convert vecotrs to a table but I am not sure how to include three categories in one plot.

How can I get a scatter plot with three different colors? I would like to set x-axis as class_day above and y axis as scores.

CodePudding user response:

First, A cleaner way to make a dataframe without the intermediate variables.

You can make this type of chart by pivoting the data into "long" form:

class.df<-data.frame(class_day = c(1:10),
                     control_group     = c(67,72,69,81,73,66,71,72,77,71), 
                     A_treatment_group = c(NA,72,77,81,73,85,69,73,74,77),
                     B_treatment_group = c(NA,66,68,69,67,72,73,75,79,77) )
library(tidyverse)
class.df %>% 
  pivot_longer(!class_day) %>% 
  ggplot(aes(x=class_day, y=value, color=name)) 
  geom_point()

enter image description here

CodePudding user response:

Here is a version with ggscatter from ggpubr:

library(ggpubr)
library(tidyverse)

class.df %>% 
  pivot_longer(-class_day,
               names_to= "group", 
               values_to = "score") %>% 
  ggscatter(x = "class_day", y = "score", color = "group",
          palette = c("#00AFBB", "#E7B800", "#FC4E07"))

enter image description here

  • Related