R 语言里面的日期环境设置和绘图中日期的显示

昨天有个小伙伴遇到了这样的一个问题,他想把图的 x 轴轴标签设置成下面这样:

注意:我和他的电脑都是 Mac 系统的,Windows 系统请看文末的提示以及参考 ?Sys.setlocale。

我随手造了个数据:

library(tidyverse)
library(lubridate)
library(scales)
tibble(
x = 1:100,
y = runif(100, 1, 10)
) %>%
mutate(date = ymd("2020-01-01") + days(x)) %>%
ggplot(aes(date, y)) +
geom_line()

我们试试设置 x 轴:

tibble(
x = 1:100,
y = runif(100, 1, 10)
) %>%
mutate(date = ymd("2020-01-01") + days(x)) %>%
ggplot(aes(date, y)) +
geom_line() +
scale_x_date(breaks = date_breaks(),
labels = date_format("%b %Y")) +
theme(axis.text.x = element_text(angle = 90))

不行,再试试这样:

tibble(
x = 1:100,
y = runif(100, 1, 10)
) %>%
mutate(date = ymd("2020-01-01") + days(x)) %>%
ggplot(aes(date, y)) +
geom_line() +
scale_x_date(breaks = date_breaks(),
labels = date_format("%B %Y")) +
theme(axis.text.x = element_text(angle = 90))

emmm,中文???

这是因为最近我又把自己电脑的语言调成了中文,这样 R 的日期环境就也是中文的了,所以我们可以先把 R 的日期环境设置成英文的:

Sys.setlocale("LC_TIME", "en_US.UTF-8")
tibble(
x = 1:100,
y = runif(100, 1, 10)
) %>%
mutate(date = ymd("2020-01-01") + days(x)) %>%
ggplot(aes(date, y)) +
geom_line() +
scale_x_date(breaks = date_breaks(),
labels = date_format("%b %Y")) +
theme(axis.text.x = element_text(angle = 90))

或者:

Sys.setlocale("LC_TIME", "en_US.UTF-8")
tibble(
x = 1:100,
y = runif(100, 1, 10)
) %>%
mutate(date = ymd("2020-01-01") + days(x)) %>%
ggplot(aes(date, y)) +
geom_line() +
scale_x_date(breaks = date_breaks(),
labels = date_format("%B %Y")) +
theme(axis.text.x = element_text(angle = 90))

如果你希望自己的 R 总是使用英文的日期环境,可以将设置代码放到 Profile 文件里面:

# 创建或打开 Profile 文件
usethis::edit_r_profile()
# 将下面的代码写入该文件:
Sys.setlocale("LC_TIME", "en_US.UTF-8")
# 然后保存

对于 Windows 电脑可能是这样设置的:

Sys.setlocale("LC_TIME", "American")

点击这里跳转到 RStata 短书平台获取附件:R 语言里面的日期环境设置和绘图中日期的显示

评论