3

I am using ggplot2 to produce a fairly simple plot of a proportion against an integer valued predictor. I am using geom_errorbar to display uncertainty for each point estimate.

e.g.

require(ggplot2)
mydata <- data.frame(my_x = 70:99, 
                     my_y = seq(0.7,0.3,length.out=30), 
                     my_lower = seq(0.6,0.2,length.out=30), 
                     my_upper = seq(0.8,0.4,length.out=30))

ggplot(mydata,aes(x=my_x)) + geom_point(aes(y=my_y)) +
                           geom_errorbar(aes(ymin=my_lower, ymax=my_upper)) +
                           xlim(70,80)

For largely aesthetic reasons I am using xlim() to set the x-axis limits (as you do). But this removes the horizontal lines indicating the limits of the error bars at the min and max x-values. I presume this is because ggplot2 is trying to draw a line which lies outside of the plot region (the function call prints some warnings from geom_path about missing values).

badggplot

I could clean the data of the unwanted rows beforehand or include a subset statement in the ggplot call, but I feel like there is/should be a cleaner solution when zooming into a plot. Any ideas?

Community
  • 1
  • 1
peedeerich
  • 253
  • 3
  • 10

3 Answers3

3

Bit hacky but it seems to work:

ggplot(mydata,aes(x=my_x)) + geom_point(aes(y=my_y)) +
                           geom_errorbar(aes(ymin=my_lower, ymax=my_upper)) +
                           coord_cartesian(xlim=c(69.5,80.5))
Tumbledown
  • 1,887
  • 5
  • 21
  • 33
  • This works, but you are right it seems a bit hacky. Having browsed similar problems online it appears subsetting the data is the optimal solution, though I think it would be nice for this to be dealt with separately from the data. Ta – peedeerich Jun 23 '14 at 10:47
0

You can try reduce the width of the error bar.

ggplot(mydata,aes(x=my_x)) + geom_point(aes(y=my_y)) +
                           geom_errorbar(aes(ymin=my_lower, ymax=my_upper),width=0.25)
Koundy
  • 5,265
  • 3
  • 24
  • 37
0

Had a similar issue with doing this with a date scale, where I was specifying the following arguments:

scale_x_date(date_labels="%Y %B", 
               date_breaks = "1 month",
               limits=as.Date(c("2020-03-01", "2021-11-01"), format="%y-%m-%d"),
               )

Eventually solved the problem with:

scale_x_date(date_labels="%Y %B", 
                   # date_breaks = "1 month",
                   limits=as.Date(c("2020-03-01", "2021-11-01"), format="%y-%m-%d"),
                   breaks = seq(as.Date("2020-03-01"), as.Date("2021-11-01"), by="months"))
Guilherme
  • 63
  • 7