自定义缩放x年QTR,以在ggplot2中设置特定间隔和结束日期
给定数据集自定义缩放x年QTR,以在ggplot2中设置特定间隔和结束日期,r,ggplot2,R,Ggplot2,给定数据集df,如下所示: structure(list(date = structure(c(14699, 14790, 14882, 14974, 15064, 15155, 15247, 15339, 15430, 15521, 15613, 15705, 15795, 15886, 15978, 16070, 16160, 16251, 16343, 16435, 16525, 16616, 16708, 16800, 16891, 16982, 17074, 17166, 172
df
,如下所示:
structure(list(date = structure(c(14699, 14790, 14882, 14974,
15064, 15155, 15247, 15339, 15430, 15521, 15613, 15705, 15795,
15886, 15978, 16070, 16160, 16251, 16343, 16435, 16525, 16616,
16708, 16800, 16891, 16982, 17074, 17166, 17256, 17347, 17439,
17531, 17621, 17712, 17804, 17896, 17986, 18077, 18169, 18261,
18352, 18443), class = "Date"), value = c(12.2, 11.4, 10.9, 10.6,
10.2, 10.1, 9.9, 9.6, 8.1, 7.9, 7.8, 7.9, 7.9, 7.7, 7.8, 7.8,
7.5, 7.6, 7.5, 7.4, 7.1, 7.1, 7.1, 7, 6.9, 6.9, 6.8, 6.8, 7,
7, 7, 6.9, 6.9, 6.9, 6.8, 6.7, 6.4, 6.3, 6.2, 6.1, -6.8, 3.2)), class = "data.frame", row.names = c(NA,
-42L))
我用下面的代码绘制了它:
df$date <- as.yearqtr(df$date, format = "%Y-%m-%d")
df_m <- melt(df, id.vars='date')
ggplot() +
geom_line(data = df_m, aes(x = date, y = value, col = variable), alpha = 0.8, size = 1) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
scale_x_yearqtr(format = "%YQ%q", breaks = df$date, n = 12, expand = c(0, 0))
df$date您可以选择每秒一次的“日期”作为breaks
:d$qtr[c(FALSE,TRUE)]
。旁注:因为“df”已经是一个长格式,所以没有必要使用melt
。你的意思是使用scale\u x\u yearqtr(format=“%YQ%q”,breaks=df$qtr[c(FALSE,TRUE)],n=12,expand=c(0,0))
?我测试过,它似乎不起作用。我测试过你的数据,它起作用了。请注意,我在尝试代码时为季度创建了一个新变量,df$qtr
。也许您在季度中还有另一个名字,df$date
?如果是这样,您当然应该相应地修改代码。抱歉搞混了请随便写一个答案。干杯您可以选择每秒一次的“日期”作为中断
:d$qtr[c(FALSE,TRUE)]
。旁注:因为“df”已经是一个长格式,所以没有必要使用melt
。你的意思是使用scale\u x\u yearqtr(format=“%YQ%q”,breaks=df$qtr[c(FALSE,TRUE)],n=12,expand=c(0,0))
?我测试过,它似乎不起作用。我测试过你的数据,它起作用了。请注意,我在尝试代码时为季度创建了一个新变量,df$qtr
。也许您在季度中还有另一个名字,df$date
?如果是这样,您当然应该相应地修改代码。抱歉搞混了请随便写一个答案。干杯