首页 > 解决方案 > 按月绘制最低和最高温度

问题描述

我对使用 R 非常陌生。我想创建一个堆积条形图,显示温度读数 <38C 或 >=38C 作为时间函数的比例。

Date    Temperature (C) 
10/22/18 8:00   36.8
10/22/18 12:00  36.8
10/22/18 16:00  36.8
10/23/18 12:00  36.8
10/30/18 16:00  36.8
10/22/18 0:00   36.9
10/29/18 20:00  36.9
10/31/18 8:00   36.9
10/18/18 4:00   37
10/20/18 20:00  37
10/21/18 20:00  37
10/30/18 4:00   37
6/15/18 20:00   36.7
6/16/18 4:00    37
6/16/18 8:00    37.1
6/16/18 12:00   37.1
6/16/18 16:00   37.1
6/16/18 0:00    37.4
4/27/18 20:00   36.4
4/28/18 0:00    36.5
4/28/18 4:00    36.5
4/27/18 18:00   36.7
4/28/18 8:00    36.8
7/31/18 0:00    36.6
8/1/18 4:00     36.6
7/31/18 8:00    36.8
7/31/18 12:00   36.8
7/31/18 16:00   36.8
8/1/18 8:00     36.8
7/30/18 20:00   36.9
7/31/18 4:00    36.9

我尝试了各种不同的代码,但它们似乎效果不佳。这是我最近尝试过的。

ggplot(master, aes(event, mastertemps)) + 
 geom_line() + 
 ylim(c(0, 1)) + 
 xlab("") + 
 ylab("Temperature") + 
 scale_x_date(date_breaks = "1 month", date_labels = "%b %y") + 
 theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
 ggtitle("2018 Temperatures")

这是我运行时收到的错误消息

“输入无效:date_trans 仅适用于 Date 类的对象”

我想要一个看起来类似于这样的情节:

每月最高和最低温度

标签: rggplot2

解决方案


这是根据您提供的样本数据绘制每日最小值-最大值的方法:

library(tidyverse)
dat <- read.csv("test.csv") # stored your sample data as a csv

dat <- dat %>% mutate(date = as.Date(Date, format="%m/%d/%y %H:%M")) # new variable in Date class

d2 <- dat %>% group_by(date) %>% summarise(min = min(Temperature), max = max(Temperature)) # new variables with min and max daily temperature

d2 <- d2 %>% gather(var, val, -date) # change the data to long format


ggplot(d2, aes(date, val, colour=var)) + geom_line() + geom_point() # plot

在此处输入图像描述

以每月最小-最大格式绘制每日:

d3 <- dat %>% 
  mutate(date = as.Date(Date, format="%m/%d/%y %H:%M")) %>% 
  mutate(month = format(date, "%m")) 

d3 <- d3 %>% group_by(month) %>%  summarise(min = min(Temperature), max = max(Temperature))

d3 <- d3 %>% gather(var, val, -month)

d3$month <- as.numeric(d3$month)

ggplot(d3,aes(month, val, colour=var)) + 
  geom_line() + 
  geom_point() + 
  scale_x_continuous("Month", breaks=seq(4, 10, 2), labels=c("Apr", "Jun", "Aug", "Oct")) +
  ylab("Temperature")

在此处输入图像描述


推荐阅读