Problems plotting timeline with different dates in ggplot

I am plotting data from two different years (07 and 08) on top of each other. These two years have slightly different dates, but when I plot this in R I cannot get all the dates, R rearranges them in descending order, or splits them into two different years one after the other with a space between them.

I need them on top of each other, some of them are slightly skewed.

The dates must be:

data_07 [1] <-c ("7/6", "21/6", "31/6", "14/7", "28/7", "11/8", "25/8", "8/9")

data_08 [1] <-c ("7/6", "21/6", "5/7", "19/7", "2/8", "16/8", "25/8", "8/9")

My script

data7 <- data.frame(
         Date = c("7/6","21/6","31/6","14/7","28/7","11/8","25/8","8/9"),
         variable = sample(c("Age 39-40", "Age 62-63"), 8, replace = TRUE),
         value = sample(1:8)
    )


data8 <- data.frame(
         Date = c("7/6","21/6","5/7","19/7","2/8","16/8","25/8","8/9"),
         variable = sample(c("Age 39-40", "Age 62-63"), 8, replace = TRUE),
         value = sample(1:8)
    )


p1<-ggplot(data7, 
    aes(x=Date, y=value, group=variable)) + 
    geom_point(size=2, shape = 15) +
    geom_line(linetype=1) +

    geom_line(data=data8, aes(x=Date, y=value, group=variable),linetype=2) +
    geom_point(data=data8, size=2, shape = 1)


 p1 + facet_wrap( ~ variable, nrow = 5, ncol = 1, scales= "fixed") +
    labs(x="Dates", y="Catches per 20 traps", title="") +
    theme(panel.grid.minor.y = element_blank(),
    panel.grid.major.y = element_blank())

      

Any help and suggestions are greatly appreciated. Thank!

Daniel

+3


source to share


2 answers


If the year is not important to the plot, I would recommend assigning a new column in the data indicating the year, converting your entire date to a total year, and then building them in groups.



library(dplyr)
library(ggplot2)
library(lubridate)

#* dates are initially stored in dd/mm format.
#* create a variable where year = 2007
#* turn all dates to dd/mm/2000
data_07 <- data.frame(date = c("7/6","21/6","31/6","14/7","28/7","11/8","25/8","8/9"),
                      y = rnorm(8),
                      stringsAsFactors=FALSE) %>%
  mutate(year = 2007,
         date = dmy(paste0(date,"/2000")))


data_08 <- data.frame(date = c("7/6","21/6","5/7","19/7","2/8","16/8","25/8","8/9"),
                      y = rnorm(8),
                      stringsAsFactors=FALSE) %>%
  mutate(year = 2008,
         date = dmy(paste0(date,"/2000")))

both_years <- bind_rows(data_07, data_08)

ggplot(data = both_years,
       mapping = aes(x = date,
                     y = y,
                     colour = factor(year))) + 
  geom_point() + 
  geom_line()

      

+1


source


These two lines solved my problem:



data$Date<-as.Date(data$Date, format="%d/%m/%Y")

scale_x_date(labels = date_format("%d/%m")) 

      

0


source







All Articles