简体   繁体   English

R并排箱线图

[英]R Side-by-Side Boxplot

I'm sure this is a very simple question for most of you, but I'm new and can't figure it out. 我敢肯定,对于大多数人来说,这是一个非常简单的问题,但是我是新手,无法解决。 How do you create a side by side box plot grouped by time? 如何创建按时间分组的并排箱图? For example, I have 24 months of data. 例如,我有24个月的数据。 I want to make one box plot for the first 12 months, and another for the second 12 months. 我想在前12个月中绘制一个箱形图,然后在接下来的12个月中绘制另一个箱形图。 My data can be seen below. 我的数据如下所示。

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

Since your data has a time ordering, it might be illuminating to plot line plots by month for each year separately. 由于您的数据具有时间顺序,因此按年度分别按月绘制折线图可能很有启发。 Here is code for both a line plot and a boxplot. 这是折线图和箱线图的代码。 I just made up the year values in the code below, but you can make those whatever is appropriate: 我只是在下面的代码中组成了年值,但是您可以根据需要进行设置:

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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM