0
votes

I have a dataframe where column 1 are Months, column 2 are Years and column 3 are precipitation values. I want to plot the precipitation values for EACH month and EACH year. My data goes from at January 1961 to February 2019. ¿How can I plot that? Here is my data:

enter image description hereIf I use this: plot(YearAn,PPMensual,type="l",col="red",xlab="años", ylab="PP media anual")

I get this:

enter image description here

Which is wrong because it puts all the monthly values in every single year! What Im looking for is an x axis that looks like "JAN-1961, FEB1961....until FEB-2019"

2

2 Answers

0
votes

It can be done easily using ggplot/tidyverse packages.

First lets load the the packages (ggplot is part of tidyverse) and create a sample data:

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

Now we can plot the data (df):

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

enter image description here

0
votes

Using lubridate and ggplot2 but with no grouping:

Setup

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

Graph

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

img