首页 > 解决方案 > 更改轴上的日期刻度的问题 - ggplot

问题描述

我有以下

data.frame
date     ratio
 1992-1    0.5
 1992-1    0.6
 1992-1    0.5
 1992-2    0.7
 1992-2    0.65
 1992-2    0.65

我尝试运行以下代码来创建图表

occratiocomb <- ggplot() +
  # blue plot
  geom_line(data=SKILL_1_OCC_FINAL, aes(x=Date, y=ratio_1occ_comb, group = 1, colour="very low")) + 
  geom_smooth(data=SKILL_1_OCC_FINAL, aes(x=Date, y=ratio_1occ_comb), method = loess, fill="red",
              colour="red", size=1) + theme(axis.text.x=element_text(angle=60, hjust=1))


# PROBLEM
occratiocomb + scale_x_date(date_breaks = "1 year", date_labels = "%Y")
print(occratiocomb)

我的图表的 x 轴(日期)看起来很糟糕,因为我有月度数据,而且它显示了 30 年的周期。我现在尝试做的事情是将日期刻度从基于月的刻度更改为基于年的刻度。不幸的是,如果我尝试运行代码,则会显示错误 date_trans 仅适用于 Date 类的对象。在我看来,这很奇怪,因为我的日期列已经是日期格式。还是与我的日期变量不包含任何日期的事实有关?

非常感谢提前 Xx Freddy

标签: r

解决方案


问题似乎是由于您的日期列的格式(正如您所怀疑的那样);如果您使用例如 lubridate 更改格式,则中断按预期工作:

library(tidyverse)
#install.packages("lubridate")
library(lubridate)

SKILL_1_OCC_FINAL <- tibble::tribble(
   ~date, ~ratio,
   "1990-1",    "0.5",
   "1990-2",    "0.6",
   "1990-3",    "0.5",
   "1991-1",    "0.7",
  "1991-2",    "0.65",
  "1991-3",    "0.65"
  )
SKILL_1_OCC_FINAL$date <- lubridate::ym(SKILL_1_OCC_FINAL$date)

occratiocomb <- ggplot(SKILL_1_OCC_FINAL, aes(x = date, y=ratio, group = 1)) +
  geom_line() + 
  geom_smooth(method = "loess", fill = "red", colour = "red") +
  theme(axis.text.x=element_text(angle = 60, hjust = 1)) +
  scale_x_date(date_minor_breaks = "1 month",
               date_breaks = "1 year",
               date_labels = "%Y-%m")
print(occratiocomb)

例子.png


推荐阅读