r - 更改轴上的日期刻度的问题 - 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
解决方案
问题似乎是由于您的日期列的格式(正如您所怀疑的那样);如果您使用例如 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)
推荐阅读
- excel - 根据另一个工作表中单元格中的值合并特定数量的单元格
- compilation - qemu 无法引导内核版本 2.6.34.7
- excel - VBA 按钮可深入到数据透视表
- javascript - 反应变量值更改不更新反应组件
- r - 从转移矩阵创建马尔可夫链对象
- javascript - 如何在 Array 对象中重复更改值
- apostrophe-cms - 如何从控制器渲染 nunjucks 模板
- c# - 为什么 IAsyncResult 返回此错误?System.PlatformNotSupportedException:“此平台不支持操作。”
- sql - SQL 返回错误结果
- rxjs - RxJS 为每个订阅者调用带有 shareReplay 的最终操作符