Home > Net >  Color-code and label ggplot graph line based on a condition in R
Color-code and label ggplot graph line based on a condition in R

Time:11-12

My ggplot() below shows the changes in variable Ratio over three Years across ids in my data.

I was wondering how to label (indicating id name) and color-code (in red) the id lines when there is a decrease across any two Years?

For example, for the line in the middle (id label A), we see a decrease from yr2019-yr2020.

So, we want to color-code that piece of line in red and label the line with its id (see pic below).

Is this possible in R?

library(tidyverse)
m="
id Year  Ratio
A  yr2019  .5
A  yr2020  .3
A  yr2021  .4
B  yr2019  .2
B  yr2020  .2
B  yr2021  .1
C  yr2019  .6
C  yr2020  .7
C  yr2021  .9"

data <- read.table(text= m, h= TRUE)

ggplot(data, aes(Year, Ratio, group= id))   geom_line()

enter image description here

CodePudding user response:

This is possible using the color attribute in the geom_line() function. The tricky part is properly setting the color for the first point of each segment. To make tracking and debugging easier, I added a color column to the original data frame.

data <- structure(list(id = c("A", "A", "A", "B", "B", "B", "C", "C", "C"), 
                       Year = c("yr2019", "yr2020", "yr2021", "yr2019", "yr2020", 
                                "yr2021", "yr2019", "yr2020", "yr2021"), 
                       Ratio = c(0.5, 0.3, 0.4, 0.2, 0.2, 0.1, 0.6, 0.7, 0.9)),
                  class = "data.frame", row.names = c(NA, -9L))

library(dplyr)
library(ggplot2)
#sort by id and Year
#if the next value is less then set color to red, if greater then set to red
data <- data %>% arrange(id, Year) %>% group_by(id) %>% mutate(color = ifelse(lead(Ratio) >= Ratio, "green", "red"))
#set last value of each group to black as default
data$color[is.na(data$color)] <- "black"

#plot
ggplot(data, aes(Year, Ratio, group= id))   
   geom_line(aes(color=color))    #or geom_line(color=data$color)
   scale_color_identity()

enter image description here

  • Related