【问题标题】:How to plot monthly data having in the x-axis months and Years R studio如何绘制 x 轴月份和 Years R studio 中的月度数据
【发布时间】:2020-11-04 03:13:55
【问题描述】:

我有一个数据框,其中第 1 列是月,第 2 列是年,第 3 列是降水值。 我想绘制每个月和每个年的降水值。 我的数据从 1961 年 1 月到 2019 年 2 月。 ¿ 我怎么能画出来? 这是我的数据:

如果我使用这个: plot(YearAn,PPMensual,type="l",col="red",xlab="años", ylab="PP media anual")

我明白了:

这是错误的,因为它将所有月值都放在每一年!我正在寻找的是一个看起来像“JAN-1961, FEB1961....直到 FEB-2019”的 x 轴

【问题讨论】:

    标签: r plot


    【解决方案1】:

    使用ggplot/tidyverse 包可以轻松完成。

    首先让我们加载包(ggplottidyverse 的一部分)并创建示例数据:

    library(tidyverse)
    
    set.seed(123)
    df <- data.frame(month = rep(c(1:12), 2), 
                     year = rep(c("1961", "1962"), 
                                each = 12), 
                     ppmensual = rnorm(24, 5, 2))
    

    现在我们可以绘制数据(df):

    df %>% 
      ggplot(aes(month, ppmensual, 
                 group = year, 
                 color = year)) + 
      geom_line()
    

    【讨论】:

      【解决方案2】:

      使用lubridateggplot2 但没有分组:

      设置

      library(lubridate) #for graphic
      library(ggplot2) # for make_date()
      
      
      df <- tibble(month = rep(month.name, 40),
                   year = rep(c(1961:2000), each = 12),
                   PP = runif(12*40) * runif(12*40) * 10) # PP data is random here
      
      print(df, n = 20)
      
         month      year     PP
         <chr>     <int>  <dbl>
       1 January    1961 5.42  
       2 February   1961 0.855 
       3 March      1961 5.89  
       4 April      1961 1.37  
       5 May        1961 0.0894
       6 June       1961 2.63  
       7 July       1961 1.89  
       8 August     1961 0.148 
       9 September  1961 0.142 
      10 October    1961 3.49  
      11 November   1961 1.92  
      12 December   1961 1.51  
      13 January    1962 5.60  
      14 February   1962 1.69  
      15 March      1962 1.14  
      16 April      1962 1.81  
      17 May        1962 8.11  
      18 June       1962 0.879 
      19 July       1962 4.85  
      20 August     1962 6.96 
      # … with 460 more rows
      

      图表

      df %>% 
        ggplot(aes(x = make_date(year, factor(month)), y = PP)) + 
        geom_line() +
        xlab("años")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 2019-02-19
        • 2013-07-07
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 2019-09-09
        相关资源
        最近更新 更多