What determines the parent in ggplot "normalized parent coordinates"?

Viewed 157

In this example, the position of the statistics text is given in "normalized parent coordinates" (NPC):

ggplot2::ggplot(data.frame(x = c(2, 3, 4), y = c(2, 2.5, 4)), 
    aes(x = x, y = y)) +
    ggplot2::coord_cartesian(xlim = c(1, 5), ylim = c(1, 5)) +
    ggpubr::stat_cor(label.x.npc = 0, label.y.npc = 1)

However, the label does not start at (1, 5) as one might think (if the cartesian coordinate system where the parent), but at (2, 4), the limits of the data. Why is that so? What determines the parent in NPC?

enter image description here

1 Answers

Update:

This is a summary of Christophe Nicault's knowledge provided in a fantastic manner here https://www.christophenicault.com/post/npc_ggplot2/.

  • In ggplot2 the coordinate system (cartesian) is used to place the elements in the plot. This is sufficient if you work with one plot.
  • In case of multiple plots or elements to be placed a relative scale to a parent element is used. For this task we use a different coordinate system called “Normalized Parent Coordinates” or NPC.

Defintion: NPC = Normalized Parent coordinates -> parent coordinates normalized from 0 to 1.

  • The origin is (0, 0) e.g. bottom left corner
  • Top right corner is at the coordinate (1, 1)
  • The maximum size is 1 of both axis

For example: The origin of npc viewport is (0,0) with a width and height of 1 unit (e.g. (0.5, 0.5) is the centre of the viewport).

First answer With this code stat_cor(method = "pearson", label.x = 1, label.y = 5) you can position the parameters whereever you want in your cartesian

library(ggpubr)
ggplot2::ggplot(data.frame(x = c(2, 3, 4), y = c(2, 2.5, 4)), 
                aes(x = x, y = y)) +
  ggplot2::coord_cartesian(xlim = c(1, 5), ylim = c(1, 5)) +
  stat_cor(method = "pearson", label.x = 1, label.y = 5)

enter image description here

Related