Home > database >  How do I set different colours in geom_errorbarh depending on the value in R
How do I set different colours in geom_errorbarh depending on the value in R

Time:08-26

I would like to set different colours for geom_errorbarh, like when average_att is over 1, the colour is red, and when it is lower than -1, the colour is blue. the colour is blue.

forestdata <- data.frame(city = c("HK6", "IS2", "CR5"), 
    average_att = c(0.752007081, -4.384720798, -0.66515768), 
    average_att_lower = c(-1.284027031, -6.088057285, -3.094599095), 
    average_att_upper = c(2.073787674, -2.637218695, 1.766942459))


ggplot(forestdata, aes(average_att, city)) 
  geom_errorbarh(aes(xmax =average_att_upper, xmin = average_att_lower),size= 1,height = 0.1, colour = "cyan4")  
  geom_point(size=2,color = "black") 
  scale_x_continuous(limits= c(-6.5, 6.5)) 
  geom_vline(aes(xintercept = 0),color="darkgoldenrod2", size = 1,alpha=0.5)

CodePudding user response:

You could create an extra column that gives the colors using case_when depending on the conditions you mentioned. You can use the following code:

library(dplyr)
library(ggplot2)
forestdata %>%
  mutate(color = case_when(average_att > 1 ~ "red",
                           average_att < -1 ~ "blue",
                           TRUE ~ "cyan4")) %>%
  ggplot(aes(average_att, city)) 
  geom_errorbarh(aes(xmax =average_att_upper, xmin = average_att_lower, colour = color),size= 1,height = 0.1, show.legend = FALSE)  
  geom_point(size=2,color = "black") 
  scale_x_continuous(limits= c(-6.5, 6.5)) 
  geom_vline(aes(xintercept = 0),color="darkgoldenrod2", size = 1,alpha=0.5)  
  scale_color_manual(values = c("red" = "red", "blue" = "blue", "cyan4" = "cyan4"))

Created on 2022-08-25 with enter image description here

  •  Tags:  
  • r
  • Related