Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: modify coord_cartesian() values dynamically

Tags:

r

ggplot2

Is there a way to modify the plot coordinates using coord_cartesian() in a way that is dynamic based on the data in the ggplot call?

For example:

ggplot(cars, aes(x = speed, y = dist)) + 
geom_point() + 
coord_cartesian(xlim = c(min(.$speed), max(.$speed) + 10))

This doesn't work, nor does using .data$speed.

like image 922
jzadra Avatar asked Oct 19 '25 10:10

jzadra


1 Answers

You can use the magrittr and dplyr pipe operator (%>%) to pass data into the ggplot call.

cars %>%
  {ggplot(., aes(speed, dist)) + 
     geom_point() + 
     coord_cartesian(xlim = c(min(.$speed), max(.$speed) + 10))
  }

Note that now you need to explicitly identify the data argument at the beginning of the ggplot call using the . pronoun.

like image 162
Brian Avatar answered Oct 21 '25 23:10

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!