17

As an example, if I want to draw a plot with points 1-5 and add points 5-9, the following would work:

plot(c(1,2,3,4,5), ylim=c(0,10))
points(c(5,6,7,8,9))

However, if I don't know beforehand what numbers the to-be-added points will be (they could be 5-9, could also be 20-29), I can't set the ylim and xlim beforehand. I would like to be able to do something like the following (which does not work):

plot(c(1,2,3,4,5))
points(c(5,6,7,8,9), ylim=c(0,10)) 

Is something like this possible?

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • 1
    I would point out that the ggplot2 solutions given below do not _technically_ satisfy the OP's question, in the sense that you still have to re-render the graph _from scratch_ to see the changes. This is the same as the situation in base graphics, where you would need to build the graph from the beginning to alter the axis limits. So @BenBolker's answer is probably the most correct one. – joran May 04 '12 at 14:36
  • 1
    which is why I accepted his answer – Niek de Klein May 04 '12 at 14:52

4 Answers4

6

(Just for completeness.)

This is almost certainly impossible in R base graphics. Other answers point out that it's doable in ggplot. It might be possible in something like the playwith package, although a short bit of playing around hasn't shown me a way to do it.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
3

You can alter the axes limits in ggplot2. For example,

require(ggplot2)
data(mpg) 

g = ggplot(mpg, aes(cyl, cty)) + geom_point() + xlim(5, 8)
g
g + xlim(4,8)

As Ben Bolker mentions, in base graphics, you definitely can't do it without additional packages.

csgillespie
  • 59,189
  • 14
  • 150
  • 185
3

Would this be good enough? It treats the upper bound of ylim as a variable, but technically you would know ylim before adding the points:

my.data <- seq(0,5)
my.points <- seq(5,9)
plot(my.data, ylim=c(0,max(my.data,my.points)))
points(my.points)

You could also treat the lower bound of ylim the same way:

my.data <- seq(0,5)
my.points <- seq(5,9)
plot(my.data, ylim=c(min(my.data,my.points),max(my.data,my.points)))
points(my.points)
Mark Miller
  • 12,483
  • 23
  • 78
  • 132
2

with ggplot2 you can modify the axis:

df <-data.frame(age=c(10,10,20,20,25,25,25),veg=c(0,1,0,1,1,0,1),extra=c(10,10,20,20,25,25,90))
 g=ggplot(data=df,aes(x=age,y=veg))
 g=g+stat_summary(fun.y=mean,geom="point")
 g

then

a<-g+coord_cartesian(xlim=c(0,100))
a+geom_point(data=df,aes(x=extra,y=veg))
user1317221_G
  • 15,087
  • 3
  • 52
  • 78