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!
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()

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))

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