Resize automatically x axis when limits for the scale_x_continuous() is set

60 views
Skip to first unread message

Sergio Fernández

unread,
Jan 25, 2016, 12:30:38 PM1/25/16
to ggplot2
Good afternoon!

I would like to know if there is any functionality regarding resizing the limits shown on a ggplot()

Example:

library(ggplot2)
xAxis
=c(0,1,2,3,4,5,6,7,8,9)
yAxis
=c(0,100,50,25,200,2,3,4,5,6)
dataframe
<- as.data.frame(cbind(xAxis, yAxis))
 
ggplot
(dataframe, aes(x=xAxis, y=yAxis, group=1)) +
  geom_line
() +
  scale_y_continuous
() +
  scale_x_continuous
(limits = c(6,9))

You can see that the line can't barely be seen as it is so small, affected by that "200" value.

I would like to do something like this automatically:

ggplot(dataframe, aes(x=xAxis, y=yAxis, group=1)) +
  geom_line
() +
  scale_y_continuous
(limits = c(2,6)) +
  scale_x_continuous
(limits = c(6,9))

I would like to perform it without hard-setting the limits for the scale_y_continuous().

Thank you!

Dennis Murphy

unread,
Jan 25, 2016, 3:09:19 PM1/25/16
to Sergio Fernández, ggplot2
Hi:

One option is coord_cartesian():

library(ggplot2)
xAxis=c(0,1,2,3,4,5,6,7,8,9)
yAxis=c(0,100,50,25,200,2,3,4,5,6)
dataframe <- as.data.frame(cbind(xAxis, yAxis))

p <- ggplot(dataframe, aes(x=xAxis, y=yAxis, group=1)) +
geom_line() +
scale_y_continuous() +
scale_x_continuous(limits = c(6,9))

p
p + coord_cartesian(ylim = c(2, 6))


Dennis
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> ---
> You received this message because you are subscribed to the Google Groups
> "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Sergio Fernández

unread,
Jan 26, 2016, 3:06:39 AM1/26/16
to ggplot2, sergi...@gmail.com
So there's no way to perform it automatically inside ggplot?

OK so if I have understood you... The only way to do it semi-automatically is that I must put variables like local max and local min inside the coord_cartesian():


library(ggplot2)
xAxis=c(0,1,2,3,4,5,6,7,8,9)
yAxis=c(0,100,50,25,200,2,3,4,5,6)
dataframe <- as.data.frame(cbind(xAxis, yAxis))

limit = c(6,9)
p <- ggplot(dataframe, aes(x=xAxis, y=yAxis, group=1)) +
  geom_line() +
  scale_y_continuous() +
  scale_x_continuous(limits = limit)


p + coord_cartesian(ylim = c(min( dataframe$yAxis[limit[1]:limit[2]] ), max( dataframe$yAxis[limit[1]:limit[2]] )))
Reply all
Reply to author
Forward
0 new messages