绘制R中多年的月平均温度

时间:2019-03-06 15:38:16

标签: r ggplot2

我有一个数据框:

> DF2 Year Month mtemp 1 2013 1 5.006653 2 2013 2 7.621885 3 2013 3 11.510275 4 2013 4 17.216123 5 2013 5 20.576981 6 2013 6 23.121375 7 2013 7 23.502917 8 2013 8 21.532995 9 2013 9 19.591288 10 2013 10 15.215585 11 2013 11 10.197611 12 2013 12 6.145336 13 2014 1 4.141124 14 2014 2 8.089588 15 2014 3 14.767509 16 2014 4 18.198597 17 2014 5 19.503396 18 2014 6 21.768531 19 2014 7 22.375683 20 2014 8 20.717831 21 2014 9 19.166370 22 2014 10 14.715206 23 2014 11 9.633269 24 2014 12 5.268259 25 2015 1 3.116468 26 2015 2 5.934901 27 2015 3 11.805243 28 2015 4 17.061784 29 2015 5 19.995519 30 2015 6 21.895852 31 2015 7 22.249716 32 2015 8 21.083172 33 2015 9 19.130370 34 2015 10 15.259302 35 2015 11 9.754643 36 2015 12 5.834026

mtemp表示平均每月温度 我想绘制类似以下内容的图片:temperaturepicture

我提供的数据仅限于2013-2015年。我想绘制2013-2015年的平均每月温度(实际上我想绘制2013-2100年的数据)。因此,我想对如何实现类似于我所附图片的情节进行概述。我在ggplot中尝试实现结果,但未获得所需的输出。如何在我的x轴上将月份显示为“ jan”,“ feb”,“ mar”等?怎样在ggplot2中实现呢?谢谢!

2 个答案:

答案 0 :(得分:1)

我个人希望分两个步骤进行操作:创建数据摘要并对其进行绘图。

summary_data <- DF2 %>%
  group_by(Month) %>%
  summarise(mean_temp = mean(mtemp))

# A tibble: 12 x 2
   Month mean_temp
   <dbl>     <dbl>
 1     1      4.09
 2     2      7.22
 3     3     12.7 
 4     4     17.5 
 5     5     20.0 
 6     6     22.3 
 7     7     22.7 
 8     8     21.1 
 9     9     19.3 
10    10     15.1 
11    11      9.86
12    12      5.75

第1步

ggplot(summary_data) +
  geom_col(aes(x = factor(Month), y = mean_temp)) +
  scale_x_discrete(labels = month.abb[1:12]) +
  labs(title = "Your Title", y = "Your Y Axis", x = "Your X Axis")

第2步

rStart

example output

答案 1 :(得分:0)

dplyrggplot结合使用。

library(tidyverse)

df %>%
  mutate(month_name = case_when(
      Month == 1 ~ "jan",
      Month == 2 ~ "feb",
      Month == 3 ~ "mar")) %>%    # etc., for rest of months
  ggplot() +
  geom_col(aes(x = month_name, y = mtemp))

那应该让你入门

相关问题