问题
I am working on a data visualization project using ggplot2
.
All numbers obtained in the plot (Includes axis-x and axis-y and numbers inside the plot) are in English format like the below plot:
but I want the numbers in all plots to be Persian (e.g., ۲۰۱۵ instead of 2015).
I have many plots with different numbers. Can anyone help me to convert English numbers in the plot to Persian?
回答1:
Approach 1 - replacing numbers
I found this function you wrote in the other question:
convert_english_to_farsi <- function(x) {
persian <- "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u06F0\u06F1\u06F2\u06F3\u06F4\u06F5\u06F6\u06F7\u06F8\u06F9"
english <- "\U0030\U0031\U0032\U0033\U0034\U0035\U0036\U0037\U0038\U0039\U0030\U0031\U0032\U0033\U0034\U0035\U0036\U0037\U0038\U0039"
return(chartr(english, persian, x))
}
This actually works quite well for me (I checked here):
convert_english_to_farsi(123456)
#> [1] "۱۲۳۴۵۶"
You can just use this function as the labels
argument in most scale_*
functions in ggplot2
. For example if we want to change the y-axis labels of some plot (economics
is included in ggplot2
so this is reproducible):
library(ggplot2)
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line() +
scale_y_continuous(labels = convert_english_to_farsi)
The highest number here is supposed to be 12,000 which translates to ۱۲۰۰۰, which looks correct.
Created on 2021-02-07 by the reprex package (v1.0.0)
Approach 2 - replacing the font
Alternativly, you can use a different font that uses Persian numbers. I found one here. Download and install it in Windows. Then load it using the extrafont
package:
library(extrafont)
#> Registering fonts with R
font_import(
path = "~/Fonts", # I placed only the downloaded ttf file here so only the relevant font is imported
recursive = FALSE
)
You can check available fonts with:
fonts()
#> [1] "Persian Pager Number"
Now change the font in your ggplot2
theme like this:
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line() +
theme_minimal(base_family = "Persian Pager Number")
来源:https://stackoverflow.com/questions/66017323/convert-english-numbers-to-persian-numbers-for-ggplot