Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a mean line in ggplot2 in R

Tags:

r

ggplot2

I have a data frame like this:

df <- data.frame(Category=c("a", "b", "c", "d", "e", "f", "g", "h"), 
                 Value=c(10,15,17,8,20,23,19,7), 
                 Time=c("Time1", "Time2", "Time1", "Time3", "Time2", "Time1", "Time3", "Time1"))

I am plotting the data as text with geom_text() using the code:

library(ggplot2)

ggplot(df, aes(x=Time, y=Value, label=Category)) + 
  geom_text() + 
  theme_minimal()  

I want to add a line connecting the mean value from Time 1 to Time 3. I have tried with geom_hline() but it doesn't work.
I hope to receive some help about this. Many thanks!

like image 225
user21390049 Avatar asked Dec 31 '25 21:12

user21390049


2 Answers

Another option to get a line with the means would be to use stat_summary with fun=mean and geom="line". Additionally, as the variable mapped on x is categorical we have to explicitly set the group aes using e.g. group = 1 to get one line connecting the means.

library(ggplot2)

ggplot(df, aes(x = Time, y = Value, label = Category)) +
  geom_text() +
  stat_summary(geom = "line", fun = mean, aes(group = 1)) +
  theme_minimal()

like image 84
stefan Avatar answered Jan 02 '26 11:01

stefan


You can do this by creating an object with means for each group and then plotting a line using it as data:

means <- df %>% group_by(Time) %>% summarise(mean_val=mean(Value))

ggplot() + 
  geom_text(data=df, mapping = aes(x=Time, y=Value, label=Category)) + 
  theme_minimal() + 
  geom_line(data=means, mapping=aes(x=Time, y=mean_val, group=1))

enter image description here

like image 43
Dan Avatar answered Jan 02 '26 11:01

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!