Dekike
Dekike

Reputation: 1284

How to show the part of the errorbar lines which are within the plot margins using `ggplot2`?

I have a grid of plots, all with the same y and x-axis scale. The plots represent time in the x-axe and mean values in the y-axe with their standard errors. My problem is that some errorbars are not entirely within the plot margins, and I wonder if there is some way to represent the part of the errorlines that are within the plot margins. Below I give a fake example and code to play with:

df <- data.frame(time=seq(-15,15,1),
                 mean=c(0.49,0.5,0.53,0.55,0.57,0.59,0.61,0.63,0.65,0.67,0.69,0.71,0.73,0.75,0.77,0.79,0.77,0.75,0.73,0.71,0.69,0.67,0.65,0.63,0.61,0.59,0.57,0.55,0.53,0.51,0.49),
                 sd=c(0.09,0.087,0.082,0.08,0.023,0.011,0.010,0.009,0.008,0.007,0.006,0.005,0.004,0.003,0.002,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.010,0.011,0.023,0.08,0.084,0.087,0.09))

Plot <-  ggplot(df, aes(x=time, y=mean)) + 
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) + 
  geom_point(size=1) + 
  geom_line () +
  theme_bw() + 
  scale_y_continuous(limits = c(0.49, 0.85), breaks = c(0.5, 0.65,0.8))

Plot  

enter image description here

Upvotes: 1

Views: 594

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174278

You need to set coord_cartesian limits rather than scale_y_continuous limits:

ggplot(df, aes(x=time, y=mean)) + 
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) + 
  geom_point(size=1) + 
  geom_line () +
  theme_bw() + 
  scale_y_continuous(breaks = c(0.5, 0.65,0.8)) +
  coord_cartesian(ylim = c(0.49, 0.85))

enter image description here

Upvotes: 1

Related Questions