[英]Create multiple boxplots from a data set on the same graph in R
The table below is a small part of a data set I want to use to make three boxplots of:下表是我想用来制作三个箱线图的数据集的一小部分:
## No year month day hour PM2.5 PM10 SO2 NO2 CO O3 TEMP PRES
## 1 7345 2014 1 1 0 20.0 90.0 18.0 62.0 NA NA -1.5 1007.3
## 2 7346 2014 1 1 1 43.0 348.0 25.0 91.0 1100 1.0 -2.6 1006.9
## 3 7347 2014 1 1 2 79.0 423.0 41.0 103.0 1800 1.0 -3.0 1006.9
## 4 7348 2014 1 1 3 82.0 337.0 43.0 101.0 2100 1.0 -3.3 1006.4
## 5 7349 2014 1 1 4 124.0 594.0 59.0 130.0 2400 1.0 -2.7 1006.1
## 6 7350 2014 1 1 5 89.0 307.0 47.0 102.0 2500 1.0 -3.1 1006.6
## 7 7351 2014 1 1 6 59.0 161.0 45.0 91.0 1900 1.0 -2.6 1007.2
## 8 7352 2014 1 1 7 31.0 93.0 24.0 69.0 900 4.0 -2.9 1007.9
## 9 7353 2014 1 1 8 21.0 90.0 18.0 52.0 700 17.0 0.0 1008.8
## 10 7354 2014 1 1 9 38.0 142.0 25.0 87.0 1200 1.0 9.0 1009.6
I want to make three boxplots of the variable PM2.5 where all of them have the condition hour == 12 but one for each of the years 2014, 2015 and 2016. They also need to be on the same graph.我想制作变量 PM2.5 的三个箱线图,它们都具有条件小时 == 12,但 2014、2015 和 2016 年各有一个。它们还需要在同一个图表上。 This is what I've tried:这是我尝试过的:
plots <- data.frame(box14 = subset(dat, hour == 12 & year == 2014)$PM2.5,
box15 = subset(dat, hour == 12 & year == 2015)$PM2.5,
box16 = subset(dat, hour == 12 & year == 2016)$PM2.5)
boxplot(plots)
I just get 'error in data.frame... arguments implying a differing number of rows'.我只是得到'data.frame 中的错误...... arguments 暗示不同的行数'。 What should I change to get the boxplots I want?我应该改变什么来获得我想要的箱线图?
Here's a pretty quick solution using dplyr
and ggplot2
:这是使用dplyr
和ggplot2
的快速解决方案:
library(dplyr)
library(ggplot2)
dat %>%
as_tibble() %>%
filter(hour == 12) %>%
filter(year %in% c(2014, 2015, 2016)) %>%
ggplot(aes(x=as.factor(year), y=PM2.5)) +
geom_boxplot()
In base r:在基础 r 中:
filtered_data <- original_data[original_data$hour == 12 & original_data$year %in% c(2014,2015,2016),]
and then接着
boxplot(PM2.5~year,data=filtered_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.