Home > Software engineering >  How to group plot colors in R
How to group plot colors in R

Time:10-06

I have a plot in R using ggplot, say like the following. How can I group the plot colors, like all Control having same color, and the Treated having another color? So basically only two different colors total. Probably I need to use group aesthetics to do this.

enter image description here

CodePudding user response:

Edit

Here is a solution without using the tidyverse package:

library(ggplot2)
library(tidyr)

growth_data <- read.csv("~/Downloads/growth_data.txt", sep = "\t")
growth_data_long <- growth_data %>% pivot_longer(-`animal`, 
                                                 names_to=("Day"),
                                                 values_to=("Growth"))

growth_data_long
#> # A tibble: 60 × 3
#>    animal    Day   Growth
#>    <chr>     <chr>  <dbl>
#>  1 Control 1 Day.1   1.08
#>  2 Control 1 Day.2   1.49
#>  3 Control 1 Day.3   2.73
#>  4 Control 1 Day.4   2.81
#>  5 Control 1 Day.5   3.8 
#>  6 Control 1 Day.6   4.8 
#>  7 Control 2 Day.1   1.22
#>  8 Control 2 Day.2   1.86
#>  9 Control 2 Day.3   2.01
#> 10 Control 2 Day.4   2.53
#> # … with 50 more rows

growth_data_long$group <- gsub(x = growth_data_long$animal, pattern = " \\d ", replacement = "")


ggplot(growth_data_long, aes(x = Day, y = Growth, group = animal, color = group))  
  geom_line()  
  geom_point()

Created on 2021-10-06 by the reprex package (v2.0.1)

CodePudding user response:

You can separate your animal column so that you get the label for control or treat.

library(tidyr)
growth_data_long <- growth_data_long %>% separate(animal, into = c("group", NA), sep = " ", remove = F)

Then produce the graph the same way as before changing color=animal to color=group.

growth_data_long %>% ggplot(aes(Day,Growth, group= animal))   aes(color=group)  geom_line() 
  geom_point()
  • Related