R并排箱线图
R Side-by-Side Boxplot
我相信这对你们大多数人来说是一个非常简单的问题,但我是新手,无法弄清楚。如何创建按时间分组的并排箱线图?比如我有24个月的数据。我想在前 12 个月制作一个箱形图,在后 12 个月制作另一个箱形图。我的数据可以在下面看到。
Month,Revenue
1,94000
2,81000
3,117000
4,105000
5,117000
6,89000
7,101000
8,118000
9,105000
10,123000
11,109000
12,89000
13,106000
14,159000
15,121000
16,135000
17,116000
18,133000
19,144000
20,130000
21,142000
22,124000
23,140000
24,104000
由于您的数据有时间顺序,因此分别为每年按月绘制线图可能很有启发性。这是线图和箱线图的代码。我只是在下面的代码中编造了年份值,但您可以根据需要制作这些值:
library(ggplot2)
# Assuming your data frame is called "dat"
dat$Month.abb = month.abb[rep(1:12,2)]
dat$Month.abb = factor(dat$Month.abb, levels=month.abb)
dat$Year = rep(2014:2015, each=12)
ggplot(dat, aes(Month.abb, Revenue, colour=factor(Year))) +
geom_line(aes(group=Year)) + geom_point() +
scale_y_continuous(limits=c(0,max(dat$Revenue))) +
theme_bw() +
labs(colour="Year", x="Month")
ggplot(dat, aes(factor(Year), Revenue)) +
geom_boxplot() +
scale_y_continuous(limits=c(0,max(dat$Revenue))) +
theme_bw() +
labs(x="Year")
我相信这对你们大多数人来说是一个非常简单的问题,但我是新手,无法弄清楚。如何创建按时间分组的并排箱线图?比如我有24个月的数据。我想在前 12 个月制作一个箱形图,在后 12 个月制作另一个箱形图。我的数据可以在下面看到。
Month,Revenue
1,94000
2,81000
3,117000
4,105000
5,117000
6,89000
7,101000
8,118000
9,105000
10,123000
11,109000
12,89000
13,106000
14,159000
15,121000
16,135000
17,116000
18,133000
19,144000
20,130000
21,142000
22,124000
23,140000
24,104000
由于您的数据有时间顺序,因此分别为每年按月绘制线图可能很有启发性。这是线图和箱线图的代码。我只是在下面的代码中编造了年份值,但您可以根据需要制作这些值:
library(ggplot2)
# Assuming your data frame is called "dat"
dat$Month.abb = month.abb[rep(1:12,2)]
dat$Month.abb = factor(dat$Month.abb, levels=month.abb)
dat$Year = rep(2014:2015, each=12)
ggplot(dat, aes(Month.abb, Revenue, colour=factor(Year))) +
geom_line(aes(group=Year)) + geom_point() +
scale_y_continuous(limits=c(0,max(dat$Revenue))) +
theme_bw() +
labs(colour="Year", x="Month")
ggplot(dat, aes(factor(Year), Revenue)) +
geom_boxplot() +
scale_y_continuous(limits=c(0,max(dat$Revenue))) +
theme_bw() +
labs(x="Year")