tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.39k stars 2k forks source link

`geom_curve` curvature direction is inconsistent on flipped axes #5069

Open Torvaney opened 1 year ago

Torvaney commented 1 year ago

The direction of the curvature in geom_curve is inconsistent with respect to other plot elements. This is easy to work around, but it would be nice if it were consistent.

See the following examples:

library(ggplot2)

p <- 
  ggplot(mtcars, aes(x = drat, y = mpg)) +
  geom_point() +
  annotate("curve", x = 4.5, xend = 4.5, y = 20, yend = 15, curvature = -1)

p + ggtitle("In the base plot, the curve arcs away from the points...")


p + coord_flip() + 
  ggtitle("Flipped, the curve arcs *towards* from the points...")


p + coord_flip() + scale_y_reverse()+ 
  ggtitle("Flipped reversed, the curve arcs away from the points again!")

Created on 2022-11-30 with reprex v2.0.2

teunbrand commented 1 year ago

One special property of geom_curve(), or to be more precise grid::curveGrob(), is that the coordinates of the segments along the curve are unknown until it is drawn on the device. That makes it hard to precisely control those coordinates inside ggplot2.

I've played around with this issue a bit, and while it would be possible to change the sign of the curvature parameter when using coord_flip(), that still leaves some inconsistency with regards to reversed scales.

In theory, it should be possible to add a third point that won't be drawn, but that forms a triangle with the start and end of the segments. If that point has changed sides relative to the start and end coordinates during transformation, the curvature could be assigned the opposite sign.

However, that approach would have the downside that the third point would affect scale training, which is not ideal, so we'd be fixing a problem by introducing another one. Unfortunately, I can't really see an elegant solution to this issue.

Torvaney commented 1 year ago

Thanks @teunbrand - I understand, and appreciate you looking into it.