Creating a bare bones number line with the min, max, and median plotted along with the average for a second layer as a point on the line. I'd like to be able to change the color of the point depending on its relative position to the median.
Here is some example data:
library(tidyverse)
df <- data.frame(
species = rep(c('dog','cat'),5),
trait = 'weight',
value = sample(5:25, 5))
df %>%
ggplot(aes(value,trait)) +
stat_boxplot(geom = "errorbar", width = 0.5) +
stat_summary(fun=median, geom="segment", aes(xend=..x.., yend=1.25, y = 0.75)) +
stat_summary(data = (df %>% filter(species == 'dog')), fun=mean,
geom="point", size=4,
shape = 15,
color = 'green') + # i'd like to change thhis color
theme_minimal() +
theme(line = element_blank(), text = element_blank())
Currently this is my plot where the point is always green. I'd like to change it to red if the point was less than the median.
Below is a version that works, but I am wondering if there is anything cleaner and more efficient? Ideally something where I can directly compare the x value of the point and directly compare to the x value of the segment created in the prior stat_summary layer.
something along the lines of this pseduocode
ifelse(point.x > segment.x, 'green', 'red')
current code:
color = ifelse(mean(test %>%
filter(species == 'dog') %>%
pull(value)) >
mean(test %>% pull(value)),
'green', 'red'))


