首页 > 解决方案 > 如何在 ggplot 的 scale_x_date 中使用罗马数字?

问题描述

我需要将格式字符串“2016-06-29”更改为:29.V.2016 我尝试过:

scale_x_date(date_labels = paste("%d", as.roman("%m"), "%Y", sep = "."))

但我得到的唯一结果是:错误:无效输入:date_trans 仅适用于 Date 类的对象此外:警告消息:在 .roman2numeric(x) 中:无效罗马数字:%m

标签: rggplot2roman-numerals

解决方案


实现所需结果的一种选择是labels通过scale_x_date. 在下面的代码中,我使用自定义函数将日期转换为您想要的格式,并使用罗马文字为月份:

library(ggplot2)

date_roman <- function(x, sep = ".") {
  paste(format(x, "%Y"), as.roman(as.numeric(format(x, "%m"))), format(x, "%d"), sep = sep)
}  

x <- as.Date("2016-06-29")
date_roman(x)
#> [1] "2016.VI.29"

ggplot(subset(economics, as.numeric(format(date, "%Y")) == 2000), aes(date, psavert)) +
  geom_line() +
  scale_x_date(labels = date_roman)


推荐阅读