[R] ggplot2 + coord_cartesian + automatic ylim

Daniel Nordlund djnord|und @end|ng |rom gm@||@com
Mon Dec 14 00:36:22 CET 2020


On 12/13/2020 12:49 PM, Brian Beckage wrote:
> As an example to illustrate my question, if I used the following code to plot the price of Apple stock using the tidyquant package and ggplot2
>
>
> AAPL<-tq_get(x="AAPL")
>
> AAPL %>%
>    ggplot(aes(x = date, y = close)) +
>    geom_line() +
>    labs(title = "AAPL", y = "Closing Price", x = "") +
>    coord_x_date(xlim=c(end-weeks(10),end),ylim=c(100,150)) +
>    theme_tq()
>
> but I would like the ylim to be set automatically based on the xlim.  In base R, this is a simple thing to do. ggplot is still a bit mysterious to me (not alway clear how it works) and so I would like to automatically set the ylim range based on the xlim range,  something  like the following, though it obviously does not work:
>
>
> AAPL<-tq_get(x="AAPL")
>
> AAPL %>%
>    ggplot(aes(x = date, y = close)) +
>    geom_line() +
>    labs(title = "AAPL Line Chart", y = "Closing Price", x = "") +
>    coord_x_date(xlim=c(end-weeks(10),end),ylim=c(min(y),max(y)) +
>    theme_tq()
>
> where the y vector corresponds to the y range delimited by xlim.  Note that coord_x_date is a wrapper for coord_cartesian.
>
> So how do I ’see’ and use the data and parms being utilized by ggplot to set the ylim?  Or more generally, how do you step through code like to this to examine for instance what exactly coord_x_date is doing?
>
> Thanks,
> Brian
>
>
>
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Brian,

I couldn't get your code to work, so I modified it slightly. Someone 
more adept at ggplot than me may be able to give you a better solution.

xmax<-AAPL$date[nrow(AAPL)]
xminmax <- c(xmax-weeks(10), xmax)
yminmax <- with(AAPL, range(AAPL[date>=xmin & date<=xmax,]$close))

AAPL %>%
   ggplot(aes(x = date, y = close)) +
   geom_line() +
   labs(title = "AAPL", y = "Closing Price", x = "") +
   coord_x_date(xlim=xminmax, ylim=yminmax) +
   theme_tq()


Hope this is helpful,

Dan

-- 
Daniel Nordlund
Port Townsend, WA  USA



More information about the R-help mailing list