Change axis text direction to right-to-left
Asked Answered
T

2

7

In right-to-left languages such as Arabic and Hebrew, how can I adjust the direction of text for ggplot2 text elements? Note that I'm not talking about alignment (which is controlled by the hjust, but rather the actual direction (the equivalent to CSS direction: rtl;) in which the text is rendered. Hence, this is not a replication of this question.

Here is a min reproducible example:

library(ggplot2)
library(tibble)

example1 <- tribble(
  ~item,
  "האם יורד גשם?"
)

# or as ordinary data frame, to avoid 'tibble' dependency
example1 <- data.frame(item = "האם יורד גשם?")

ggplot(example1, aes(item)) + 
  geom_bar() + 
  theme(axis.text.x = element_text(size = 25))

I have enlarged the axis text x to illustrate what I mean. The code produces the following chart, note that the question mark is on the right side of the text and I want it to appear on the left side of the text. In the tibble example1 it's ok (even though it looks "opposite", the question mark ends the sentence.)

Change direction of element_text

Tuft answered 24/12, 2018 at 15:11 Comment(2)
theme(axis.text.x = element_text(size = 25, angle = -180)) ?Tull
Slightly related: there is currently a WIP pull request for RtL plotting on Github .Ki
L
3

You may use the Unicode control character for "RIGHT-TO-LEFT EMBEDDING" ("Treat the following text as embedded right-to-left"): u202B. See Explicit Directional Embeddings.

example1$item <- paste("\u202B", example1$item)
ggplot(example1, aes(item)) + 
   geom_bar() +
   theme(axis.text.x = element_text(size = 25))

enter image description here

Lockjaw answered 24/12, 2018 at 22:9 Comment(1)
AMAZING!, I'm utterly impressed. I didn't imagine it was that simple. Thanks!Tuft
F
0

You have to change the question mark in the original, and then it comes out ok:

library(ggplot2)
library(tibble)
example1 <- tribble(
  ~item,
  "?האם יורד גשם"
)

ggplot(example1, aes(item)) + 
geom_bar() + 
theme(axis.text.x = element_text(size = 25))
Flaunt answered 24/12, 2018 at 15:33 Comment(1)
Hi Omry, this answer is a workaround that only solves the problem in the simple case you have a simple line. Imagine having a big data file with Hebrew characters, perhaps utilizing a text wrap, i.e., with str_wrap and the wrap yields other punctuation marks (-,.?!, etc.) in other lines... This makes this workaround less practical.Tuft

© 2022 - 2024 — McMap. All rights reserved.