[R] ggplot2 + coord_cartesian + automatic ylim

David Winsemius dw|n@em|u@ @end|ng |rom comc@@t@net
Mon Dec 14 00:06:47 CET 2020


On 12/13/20 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.


Why not let ggplot do it for you by "filtering" the data down to the 
date range you expect.


AAPL %>% filter(date > end-weeks(10)) %>%
     ggplot(aes(x = date, y = close)) +
     geom_line() +
     labs(title = "AAPL", y = "Closing Price", x = "") +
     coord_x_date(xlim=c(end-weeks(10),end)) +
     theme_tq()


Might not even need `coord_x_date` call at all.

>
> 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.



More information about the R-help mailing list