[R] ggplot2 + coord_cartesian + automatic ylim

Brian Beckage Br|@n@Beck@ge @end|ng |rom uvm@edu
Mon Dec 14 01:43:02 CET 2020


David,

Great suggestion!

Thanks,
Brian






On Dec 13, 2020, at 6:06 PM, David Winsemius <dwinsemius using comcast.net<mailto:dwinsemius using comcast.net>> wrote:


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

______________________________________________
R-help using r-project.org<mailto: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.


	[[alternative HTML version deleted]]



More information about the R-help mailing list