Home > Back-end >  trying to plot two groups on the same figure using ggplot
trying to plot two groups on the same figure using ggplot

Time:11-23

I have my data like this

Name    group   median  SD
First   Mydate  12.118  2.221
First   Best1   18.806  0.721
First   Best2   22.670  0.092
Second  Mydate  22.911  0.322
Second  Best1   23.495  0.756
Second  Best2   23.028  0.685

I am trying to plot both on the same figures (First and Second name)

when I do this

gplot(mydf, aes(x = group, y = median, color=group)) 
  geom_point(size = 3)

it plot the dots

but when I want to make the line and I add this

  geom_line(color = "black",linetype="dashed", group = 1) 

it plot all dots as line

basically I want to plot it with SD like this

ggplot(mydf, aes(x = group, y = median, color=group)) 
  geom_point(size = 3)  
  geom_line(color = "black",linetype="dashed", group = 2) 
  geom_errorbar(aes(ymin = median - SD, ymax = median   SD), colour = c("Blue", "Red","green"))

but two groups on the same figure

after so much attempt, I somehow figured that I could plot it like this but still cannot assign the SD to each

ggplot(mydf, aes(x = group, y = median, color=Name))   
    geom_point()   
    geom_line(data=mytt[mytt$Name!="First", ])  
    scale_color_manual("Dataset", 
                       values = c("First" = "darkgreen", "Second" = "blue"))

CodePudding user response:

Is this your expected outcome?

library(ggplot2)

mydf <- read.table(text = "Name    group   median  SD
First   Mydate  12.118  2.221
First   Best1   18.806  0.721
First   Best2   22.670  0.092
Second  Mydate  22.911  0.322
Second  Best1   23.495  0.756
Second  Best2   23.028  0.685", header = TRUE)

mydf
#>     Name  group median    SD
#> 1  First Mydate 12.118 2.221
#> 2  First  Best1 18.806 0.721
#> 3  First  Best2 22.670 0.092
#> 4 Second Mydate 22.911 0.322
#> 5 Second  Best1 23.495 0.756
#> 6 Second  Best2 23.028 0.685

ggplot(mydf, aes(x = group, y = median, color = group))  
  geom_point(size = 3)  
  geom_line(aes(group = Name), color = "black", linetype="dashed")  
  geom_errorbar(aes(ymin = median - SD, ymax = median   SD))

Created on 2022-11-23 by the reprex package (v2.0.1)

  • Related