0

I have a data.frame with 3 variables and would like to plot two variables (VWC and Depth) related to the third one, Date, in POSIXct format. I would also like to add the POSIXct timestamp to the legend.

The structure of my data.frame is the following:

> str(paper_profile_data2)
'data.frame':   24 obs. of  3 variables:
 $ Date    : POSIXct, format: "2017-04-07 06:45:00" "2017-04-07 06:45:00" ...
 $ VWC     : num  0.267 0.248 0.299 0.263 0.262 0.314 0.242 0.244 0.308 0.166 ...
 $ Depth_cm: int  16 36 56 16 36 56 16 36 56 16 ...

I would like to obtain a figure like this one : made by Excel.

For now I managed to obtain the following figure in R: in R.

R code is the following:

paper_profile_data2 = read.csv(file= "paper_profile_data_2.csv" , header=TRUE,sep= ";")) 
paper_profile_data2$Date<- as.POSIXct(paper_profile_data2$Date,format="%d/%m/%Y %H:%M",tz="UTC")


ggplot(paper_profile_data2)+
    geom_point(aes(x=VWC,y=Depth_cm,color=Date))+
    geom_line(aes(x=VWC,y=Depth_cm,color=Date))+
    labs(x=expression (vwc ~(m^3/m^3)),y = expression ("Depth (m)"),title="") +
    scale_y_reverse(limits = c((60),(0)), breaks=c(60,56,36,16,0),expand = c(0, 0))

Any help will be highly appreciated. Thanks in advance.

Raül

PD. Thanks to Roland comment (make date as factor). I did a previous transformation of the Date variable to POSIXct, and that lead to an error. I let variable Date as Factor and the error dissapeared. Finally I changed geom_line to geom_path, so that the different points ar ordered in the original order (my data ir ordered by date and depth).

Here the final R code:

paper_profile_data2 = read.csv(file= "paper_profile_data_2.csv" , header=TRUE,sep= ";"))

ggplot(paper_profile_data2)+
    geom_point(aes(x=VWC,y=Depth_cm,color=Date))+
    geom_path(aes(x=VWC,y=Depth_cm,color=Date))+
    labs(x=expression (vwc ~(m^3/m^3)),y = expression ("Depth (cm)"),title="") +
    scale_y_reverse(limits = c((60),(0)), breaks=c(60,56,36,16,0),expand = c(0, 0)) +
    labs(x=expression (vwc ~(m^3/m^3)),y = expression ("depth (cm)"),title="")

And the:final result

Raül Oo
  • 57
  • 8
  • 1
    Make `Date` a factor or character variable. Use `strftime` to get the desired format for the factor. – Roland Jan 29 '18 at 11:27
  • Also look at the documentation for the ggplot2 function `scale_x_date()`: http://ggplot2.tidyverse.org/reference/scale_date.html – qdread Jan 29 '18 at 12:11
  • Many thanks Roland, I just loaded the data without previously transforming the Date variable to POSIXct, so i let the Date variable as factor, and it worked! – Raül Oo Jan 29 '18 at 12:36
  • Is there a way to order automatically the legend by date? It seems R is ordering the legend by day, and not by date (see final result). Many thanks. – Raül Oo Jan 29 '18 at 13:19
  • Make it an ordered factor. – Roland Jan 30 '18 at 07:08

0 Answers0