Search code examples
rbar-chartmedian

How to spot the mediane barplot in ggplot


I want to spot the centre that corresponds to the median value, in two way:

Firstly by a horizontal line passing by median centre (As I have an even number of centres, I decide to choose each time the centre corresponding two the highest of two mediane value, I this case the Centre 6)

Secondly by highlighting the color of the median barplot.

My code:

Centre <- paste("Centre", 1:10, sep= " ")
Value <- c(10, 23, 27, 50, 60, 71, 88, 102, 110, 113)
mydata<-data.frame(Centre, Value)

ggplot(mydata, aes(x=Centre, y=Value) +
       geom_col() + 
       coord_flip()

Solution

  • Try this solution:

    library(ggplot2)
    library(dplyr)
    
    Centre <- paste("Centre", 1:10, sep= " ")
    Value <- c(10, 23, 27, 50, 60, 71, 88, 102, 110, 113)
    mydata<-data.frame(Centre, Value)
    mydata <- mydata %>% 
              mutate(new_color = ifelse(Value == 71, "yes", "no"))    
      
     ggplot(mydata, aes(x=Centre, y=Value, fill = new_color)) +
            geom_col() + 
            coord_flip() +
            scale_fill_manual(values = c("yes"="black", "no"="gray"), guide = "none") + 
            geom_segment(aes(x = 7, y = 0, xend = 7, yend = 71), color="red", size=2)
    

    Result:

    enter image description here