gpt4 book ai didi

r - 使用季度数据格式化scale_x_continuous轴

转载 作者:行者123 更新时间:2023-12-04 16:28:15 24 4
gpt4 key购买 nike

我有一组统计的东西数据集,分为两组,每季度统计一次。 Date_Qtr变量来自具有lubridate的较大数据集。数据帧如下。

dat = structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("TypeA",
"TypeB"), class = "factor"), Date_Qtr = c(2011.1, 2011.2, 2011.3,
2011.4, 2012.1, 2012.2, 2012.3, 2012.4, 2013.1, 2013.2, 2013.3,
2013.4, 2014.1, 2014.2, 2014.3, 2014.4, 2015.1, 2015.2, 2011.1,
2011.2, 2011.3, 2011.4, 2012.1, 2012.2, 2012.3, 2012.4, 2013.1,
2013.2, 2013.3, 2013.4, 2014.1, 2014.2, 2014.3, 2014.4, 2015.1,
2015.2), Counts = c(105L, 82L, 72L, 79L, 93L, 118L, 81L, 96L,
84L, 83L, 84L, 81L, 99L, 103L, 111L, 80L, 127L, 107L, 54L, 51L,
64L, 64L, 53L, 65L, 78L, 63L, 92L, 61L, 80L, 71L, 88L, 66L, 67L,
57L, 75L, 59L)), .Names = c("Group", "Date_Qtr", "Counts"), class = "data.frame", row.names = c(NA,
-36L))

我在ggplot2中绘制了一个时间序列,如下所示,其中Date_Qtr变量为 scale_x_continuous。以前,当我绘制每月数据时,很容易每隔四个时间间隔分配一次休息时间。
ggplot(dat, aes(x = Date_Qtr, y = Counts)) + 
geom_point( aes( color = Group ), size = 3) +
geom_line(aes(color = Group), size = 0.8) +
scale_y_continuous("Number of things",
limits = c(0, 150)) +
scale_x_continuous("Year and quarter when things were counted") +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5),
legend.title = element_blank(),
legend.position = c(0.4, 0.85))

是否有可能以连续的比例将数据表示为每个数据点的实际四分之一,最好采用“Jan-Mar 2012”等格式。

提前致谢。

最佳答案

您可以将Date用作x轴:

library(ggplot2)
library(scales)
library(zoo)

make_date <- function(x) {
year <- floor(x)
x <- year + (x - year)/0.4 - 0.125
as.Date(as.yearqtr(x))
}

format_quarters <- function(x) {
x <- as.yearqtr(x)
year <- as.integer(x)
quart <- as.integer(format(x, "%q"))

paste(c("Jan-Mar","Apr-Jun","Jul-Sep","Oct-Dec")[quart],
year)
}


ggplot(dat, aes(x = make_date(Date_Qtr), y = Counts)) +
geom_point( aes( color = Group ), size=3) +
geom_line(aes(color = Group), size=0.8) +
scale_y_continuous("Number of things",
limits=c(0,150)) +
scale_x_date("Year and quarter when things were counted",
breaks = date_breaks("3 months"),
labels = format_quarters) +
theme_bw() +
theme(axis.text.x = element_text(angle=45, vjust = 0.5),
legend.title=element_blank(),
legend.position = c(.4,0.85))

关于r - 使用季度数据格式化scale_x_continuous轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31198144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com