Home > Enterprise >  How to make horizontal lines on a grouped bar chart that also display the average values correspondi
How to make horizontal lines on a grouped bar chart that also display the average values correspondi

Time:10-03

my code:

library(tidyverse)
library(lubridate)
library(ggplot2)

category <- c("apple", "apple", "apple","orange", "orange","orange")
mean_diameter_cm <- c(5.2,6.4,6.0, 9.2,8.6,8.1)
location <- c("Farm A","Farm B", "Farm C","Farm A","Farm B", "Farm C")
myfruit_data <- data.frame(category, mean_diameter_cm, location)

myfruit_data %>% 
    group_by(category, location) %>% 
    summarise(average_diameter = mean(mean_diameter_cm)) %>% 
    ggplot(aes(x=location, y=average_diameter, fill=category))  
    geom_col(position = "dodge")

my bar graph enter image description here

I tried manually calculated the averages for each group, added horizontal lines and colors like this:

geom_line()  
geom_hline(yintercept = mean_diameter_cm,
          color = c("green","red"))

The problem with this approach is I don't know how to manually add the corresponding legends and make average values display, and even if I do, it seems a bit too complicated for a not so sophisticated task, so I am thinking there must be simpler approach done by some functions that I am unaware of, which is why I am asking here. Thank you in advance.

CodePudding user response:

Perhaps this helps

library(dplyr)
library(ggplot2)
myfruit_data %>% 
    group_by(category) %>%
    mutate(avg = mean(mean_diameter_cm)) %>% 
    ungroup %>% 
    mutate(colr = case_when(category == "apple" ~ "green",
          TRUE ~ "red")) %>% 
    ggplot(aes(x=location, y=mean_diameter_cm, fill=category))  
    geom_col(position = "dodge")   
        geom_line()   
        geom_hline(aes(yintercept = avg, colour = colr))   
        guides(color = FALSE)

-output

enter image description here

CodePudding user response:

I am a bit unsure what you want but maybe this?

ggplot(myfruit_data, aes(x=location, y=mean_diameter_cm, fill = category))  
  geom_col(position = "dodge")     geom_hline(data = myfruit_data %>%                              
                                                group_by(category) %>%                      
                                                summarise_at(vars(mean_diameter_cm),           
                                                             list(Mean = mean)), aes(yintercept = Mean, color = category))

enter image description here

  • Related