Convert English numbers to Persian for ggplot

99封情书 提交于 2021-02-19 08:32:30

问题


I am working on a data visualization project using ggplot. I have my original data in English:

world_ecommerce <- data.frame(
    year = factor(c(2014, 2015, 2016, 2017, 2018)),
    score = c(1336, 1548, 1845, 2304, 2842)
)

I want to visualize it as a bar chart and show all numbers in persian. My original Bar chart is:

ggplot(
    world_ecommerce, 
    aes(x = year, y = score, label = score), 
    fill = "#56c7da"
) +
    geom_bar(
        stat = "identity",
        fill = "#56c7da",
        position = position_dodge(),
        width = 0.5,
        size = 0
    ) +
    geom_text(
        aes(label = score),
        vjust = -1.5,
        color = "#555555",
        position = position_dodge(width = 0.5),
        size = 3.5
    ) +
    scale_y_continuous(
        expand = c(0,0),
        limits = c(0, 3150),
        breaks = c(
            500, 1000, 1500, 2000, 2500, 3000
        )
    ) +
    xlab("سال") +
    ylab("") +
    ggtitle("میلیارد دلار") +
    labs(
        subtitle = "اندازه بازار خرده فروشی آنلاین در دنیا",
        caption = "منبع: سایت تحلیلی-پژوهشی Statista"
    )

I need the geom_text labels and axis numbers to be in Persian (e.g., ۲۰۱۵ instead of 2015).


回答1:


First, we need to write a function to translate characters from English numbers to Persian:

to_fa_numbers <- 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))
}

Then, we can easily apply it to our ggplot geoms and layers:

ggplot(
    world_ecommerce, 
    aes(x = year, y = score, label = score), 
    fill = "#56c7da"
    ) +
    geom_bar(
        stat = "identity",
        fill = "#56c7da",
        position = position_dodge(),
        width = 0.5,
        size = 0
    ) +
    geom_text(
        aes(label = to_fa_numbers(score)),
        vjust = -1.5,
        color = "#555555",
        position = position_dodge(width = 0.5),
        size = 3.5
    ) +
    scale_x_discrete(
        labels = to_fa_numbers
    ) +
    scale_y_continuous(
        expand = c(0,0),
        limits = c(0, 3150),
        breaks = c(
            500, 1000, 1500, 2000, 2500, 3000
        ),
        labels = to_fa_numbers
    ) +
    xlab("سال") +
    ylab("") +
    ggtitle("میلیارد دلار") +
    labs(
        subtitle = "اندازه بازار خرده فروشی آنلاین در دنیا",
        caption = "منبع: سایت تحلیلی-پژوهشی Statista"
    )



来源:https://stackoverflow.com/questions/60593481/convert-english-numbers-to-persian-for-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!