Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show means with points and horizontal lines (segments) with ggplot2

Tags:

r

ggplot2

I would like to plot data of three groups. Specifically, I want to show individual data points including the means of the three groups. Here's what I have so far:

library(ggplot2)

df <- data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))

ggplot(data=df, mapping=aes(x=group, y=value)) +
    geom_point() +
    stat_summary(fun="mean", geom="point", color="red", size=5) +
    stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.25, yend=..y..))

This produces the following figure:

This is what I have

However, I would like the horizontal line segments to start to the left of each group's mean instead of starting at the center. I tried specifying mapping=aes(x=..x.. - 0.25, xend=..x.. + 0.25, yend=..y..), but this just gives me an error:

Error: stat_summary requires the following missing aesthetics: x

I don't understand why I can't use ..x.. to specify the x aesthetic, whereas it works for the xend one.

Any idea how I can make the horizontal line segments symmetric around the group centers?

like image 547
cbrnr Avatar asked Oct 18 '25 19:10

cbrnr


2 Answers

Try this (Maybe not the most elegant solution):

library(ggplot2)

df <- data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))

ggplot(data=df, mapping=aes(x=group, y=value)) +
  geom_point() +
  stat_summary(fun="mean", geom="point", color="red", size=5) +
  stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. - 0.25, yend=..y..))+
  stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.25, yend=..y..))

e chec

like image 167
Duck Avatar answered Oct 21 '25 08:10

Duck


This comes up pretty high on the search and, although I think it's a clever approach, I think the way to have the summary as requested is using crossbar for the geom.

library(ggplot2)

df <- data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))

ggplot(data=df, mapping=aes(x=group, y=value)) +
  geom_point() +
  stat_summary(fun=mean, geom="point", color="red", size=5) +
  stat_summary(fun=mean, geom="crossbar")

Created on 2023-07-31 with reprex v2.0.2

like image 39
Matias Andina Avatar answered Oct 21 '25 10:10

Matias Andina