Home > Software design >  Why does the command "group" in ggplot doesn't work?
Why does the command "group" in ggplot doesn't work?

Time:03-11

library (tidyverse)
library (datarium)

data("anxiety", package = "datarium")    
   
anxiety <- anxiety %>%   
  rename(groupes = group)
  anxiety1 <- anxiety %>% 
   pivot_longer (c("t3", "t2", "t1"), names_to = "moment", 
                 values_to = "valeur") %>%   
   print ()
   
ggplot (data = anxiety1, aes (x = groupes, y = valeur,  
        colour = moment, group = moment))     
 geom_line ()     
 geom_point ()

The command "group" in ggplot2 doesn't work and give an awful chart.

CodePudding user response:

If you keep groupes on the x axis, there is no way to have lines going across the page, since each individual id only belongs to a single group. The lines would therefore all be vertical.

In your version, you have joined the dots of all individuals at a particular moment by setting moment as the grouping variable. This will join all the dots for each color in each moment, then zig-zag to the next point on the x axis, which looks ugly. However, this is exactly what setting group = moment is asking ggplot to do.

Instead, it makes more sense to have moment on the x axis, colour by groupes, and group by id:

ggplot(data = anxiety1, 
       aes (x = moment, y = valeur, colour = groupes, group = id))     
  geom_line()     
  geom_point()

enter image description here

CodePudding user response:

I would follow @Allan Cameron suggestion in this case. I managed to find the error. Basically is the way you save your result (name of the tibbles). I inserted the comments where I found the errors.

Sample code:

library (tidyverse)
library (datarium)

data("anxiety", package = "datarium")    
   
anxiety1 <- anxiety %>%   #name as anxiety1
  rename(groupes = group)

  anxiety2 <- anxiety1 %>%  # change name to anxiety2
   pivot_longer (c("t3", "t2", "t1"), names_to = "moment", 
                 values_to = "valeur") %>%   
   print ()
   
ggplot (data = anxiety2, aes (x = groupes, y = valeur,  colour = moment, group = moment))     # change to anxiety 2 
 geom_line ()     
 geom_point ()

Sample plot:

enter image description here

  • Related