Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change axis text direction to right-to-left

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

like image 523
Adi Sarid Avatar asked Dec 24 '18 15:12

Adi Sarid


People also ask

How do I change the direction of text in Axis?

In the Format Axis dialog box, click Text Options. Under Text Box, do one or more of the following: In the Vertical alignment box, click the vertical alignment position that you want. In the Text direction box, click the text orientation that you want.


1 Answers

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

like image 80
Henrik Avatar answered Sep 25 '22 16:09

Henrik