@@ -208,11 +208,12 @@ GeomText <- ggproto("GeomText", Geom,
208208 }
209209
210210 data <- coord $ transform(data , panel_params )
211+
211212 if (is.character(data $ vjust )) {
212- data $ vjust <- compute_just(data $ vjust , data $ y )
213+ data $ vjust <- compute_just(data $ vjust , data $ y , data $ x , data $ angle )
213214 }
214215 if (is.character(data $ hjust )) {
215- data $ hjust <- compute_just(data $ hjust , data $ x )
216+ data $ hjust <- compute_just(data $ hjust , data $ x , data $ y , data $ angle )
216217 }
217218
218219 textGrob(
@@ -234,11 +235,31 @@ GeomText <- ggproto("GeomText", Geom,
234235 draw_key = draw_key_text
235236)
236237
237- compute_just <- function (just , x ) {
238- inward <- just == " inward"
239- just [inward ] <- c(" left" , " middle" , " right" )[just_dir(x [inward ])]
240- outward <- just == " outward"
241- just [outward ] <- c(" right" , " middle" , " left" )[just_dir(x [outward ])]
238+ compute_just <- function (just , a , b = a , angle = 0 ) {
239+ # As justification direction is relative to the text, not the plotting area
240+ # we need to swap x and y if text direction is rotated so that hjust is
241+ # applied along y and vjust along x.
242+ if (any(grepl(" outward|inward" , just ))) {
243+ # ensure all angles are in -360...+360
244+ angle <- angle %% 360
245+ # ensure correct behaviour for angles in -360...+360
246+ angle <- ifelse(angle > 180 , angle - 360 , angle )
247+ angle <- ifelse(angle < - 180 , angle + 360 , angle )
248+ rotated_forward <-
249+ grepl(" outward|inward" , just ) & (angle > 45 & angle < 135 )
250+ rotated_backwards <-
251+ grepl(" outward|inward" , just ) & (angle < - 45 & angle > - 135 )
252+
253+ ab <- ifelse(rotated_forward | rotated_backwards , b , a )
254+ just_swap <- rotated_backwards | abs(angle ) > 135
255+ inward <-
256+ (just == " inward" & ! just_swap | just == " outward" & just_swap )
257+ just [inward ] <- c(" left" , " middle" , " right" )[just_dir(ab [inward ])]
258+ outward <-
259+ (just == " outward" & ! just_swap ) | (just == " inward" & just_swap )
260+ just [outward ] <- c(" right" , " middle" , " left" )[just_dir(ab [outward ])]
261+
262+ }
242263
243264 unname(c(left = 0 , center = 0.5 , right = 1 ,
244265 bottom = 0 , middle = 0.5 , top = 1 )[just ])
0 commit comments