Home > Software design >  How to set separate error bar colors with ggplot2?
How to set separate error bar colors with ggplot2?

Time:11-09

I want to manually control the colors of my error bars in a line plot:

col_1<-c(1:4, 1:4)
col_2<-c(25, 30, 28, 28, 35, 36, 39, 40)
er_bar<-c(3, 3, 2, 2, 2,4,4,3)
condition<-c("A","A","A","A", "B","B","B","B")
example<-data.frame(col_1, col_2, er_bar, condition)
example

ggplot(example, aes(col_1, col_2, color=condition))  geom_line(size=0.1) 
  geom_errorbar(aes(ymin=col_2-er_bar, ymax=col_2 er_bar), width=.1, color="blue")  scale_color_manual(values=c("#FF0000", "254117"))

gives me a plot with all the error bars the color blue, as specified. How do I select a separate color for each line?

CodePudding user response:

In order to map the color of your errorbars to the data, you just have to specify color as an argument to the aes function for that geom.

library(ggplot2)

col_1<-c(1:4, 1:4)
col_2<-c(25, 30, 28, 28, 35, 36, 39, 40)
er_bar<-c(3, 3, 2, 2, 2,4,4,3)
condition<-c("A","A","A","A", "B","B","B","B")
example<-data.frame(col_1, col_2, er_bar, condition)
example
#>   col_1 col_2 er_bar condition
#> 1     1    25      3         A
#> 2     2    30      3         A
#> 3     3    28      2         A
#> 4     4    28      2         A
#> 5     1    35      2         B
#> 6     2    36      4         B
#> 7     3    39      4         B
#> 8     4    40      3         B

ggplot(example, aes(col_1, col_2, color=condition))   
  geom_line(size=0.1)  
  geom_errorbar(aes(ymin = col_2-er_bar, ymax = col_2 er_bar, color=condition), width=.1)   
  scale_color_manual(values=c("#FF0000", "254117"))

Created on 2021-11-08 by the reprex package (v2.0.1)

CodePudding user response:

Here is one option, though I'd welcome a cleaner method:

example2<-example %>%
  mutate(testcol = case_when(
    endsWith(condition, "A") ~ "#F88158",
    endsWith(condition, "B") ~ "#0041C2"
  ))

errorbar_colors<-example2$testcol

ggplot(example, aes(col_1, col_2, color=condition))  geom_line(size=0.1) 
  geom_errorbar(aes(ymin=col_2-er_bar, ymax=col_2 er_bar), width=.1, color=errorbar_colors) 
  scale_color_manual(values=c("#FF0000", "254117"))
  • Related