TransWikia.com

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

Stack Overflow Asked by cbrnr on November 24, 2021

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?

One Answer

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

Answered by Duck on November 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP