[R] ggplot2 + coord_cartesian + automatic ylim

Brian Beckage Br|@n@Beck@ge @end|ng |rom uvm@edu
Sun Dec 13 21:49:26 CET 2020


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



More information about the R-help mailing list