Paula
Paula

Reputation: 693

ggplot2: drawing a line between two values

I have the following dataframe:

df <- tribble(
  ~group,   ~value,   ~ci_low,  ~ci_upper,  
  "group1", 0.0577434,  0.0567665,    0.0587203,
  "group2", 0.0941233,  0.0801769,    0.1080698)

I want to plot the column "value" as a point and then a dashed line that goes "under" which minimum point is ci_low and high point is ci_upper.

So far I have this:

ggplot(df, aes(group, value)) +
  geom_point(size = 4)

And I want something like this:

enter image description here

Upvotes: 1

Views: 231

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

To have control over the line ends, use geom_segment:

ggplot(df, aes(group, value)) +
  geom_segment(aes(xend = group, y = ci_low, yend = ci_upper), color = "red", size = 2, lineend = "round") +
  geom_point(size = 4) +
  theme_bw()

enter image description here

If square line ends are OK, use geom_linerange:

ggplot(df, aes(group, value)) +
  geom_linerange(aes(ymin = ci_low, ymax = ci_upper), color = "red", size = 2) +
  geom_point(size = 4) +
  theme_bw()

enter image description here

Upvotes: 2

Austin Graves
Austin Graves

Reputation: 1052

This should do the trick.

ggplot(df, aes(x=group, y=value)) + 
  geom_pointrange(aes(ymin=ci_low, ymax=ci_upper))

Upvotes: 1

Related Questions