Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the x and y coordinates of the corners in ggplot2?

Tags:

r

ggplot2

Here is the code:

xbreaks <- c(100, 200, 300)
ybreaks <- c(2, 3, 4, 5)
ggplot(mtcars, aes(hp, wt)) +
  scale_x_continuous(breaks=xbreaks) +
  scale_y_continuous(breaks=ybreaks) +
  geom_point()

Here is the plot:

enter image description here

How can I find the X and Y values corresponding to the bottom left-hand corner (which I've marked with a green dot)? I guess that they are approximately (40, 1.40), but can I ask R for the exact values?

like image 822
Nick Brown Avatar asked Jan 29 '23 00:01

Nick Brown


2 Answers

Yes you can! Try this:

g <- ggplot(mtcars, aes(hp, wt)) +
  scale_x_continuous(breaks=xbreaks) +
  scale_y_continuous(breaks=ybreaks) +
  geom_point()

b <- ggplot_build(g)
b$layout$panel_ranges[[1]]$x.range

[1]  37.85 349.15
like image 164
thc Avatar answered Feb 08 '23 15:02

thc


Do you want the coordinates or do you want to plot something there? To plot something there, you can use -Inf (or Inf for the opposite site) as x and y coordinates:

library(ggplot2)
xbreaks <- c(100, 200, 300)
ybreaks <- c(2, 3, 4, 5)
ggplot(mtcars, aes(hp, wt)) +
  scale_x_continuous(breaks=xbreaks) +
  scale_y_continuous(breaks=ybreaks) +
  geom_point() +
  geom_point(aes(x = -Inf, y = -Inf), color = "blue", inherit.aes = FALSE)

Notice the blue dot in the lower left corner. It is clipped by default, but you can switch off clipping to show the entire dot:

ggplot(mtcars, aes(hp, wt)) +
  scale_x_continuous(breaks=xbreaks) +
  scale_y_continuous(breaks=ybreaks) +
  geom_point() +
  geom_point(aes(x = -Inf, y = -Inf), color = "blue", inherit.aes = FALSE) +
  coord_cartesian(clip = "off")

Created on 2018-05-29 by the reprex package (v0.2.0).

like image 34
Claus Wilke Avatar answered Feb 08 '23 13:02

Claus Wilke