'R plot with date on x axis

I'm trying to plot the seasonality of nesting and hatching for turtles on one graph - with the count of how many nests were laid/hatched for every day of the season (01/05/2021-30/09/2021). Some of my data is as follows:

Date - Laid Green - Hatched Green

14/05/2021 - 0 - 0

15/05/2021- 0 - 0

16/05/2021- 0 - 0

17/05/2021- 0 - 0

18/05/2021- 0 - 0

19/05/2021 - 0 - 0

20/05/2021 -1 - 0

21/05/2021- 2 - 0

22/05/2021- 0 - 0

23/05/2021- 1 - 0

24/05/2021 - 2- 0

25/05/2021- 0 - 0

26/05/2021 -1 - 0

27/05/2021 - 4 - 0

When then trying to plot it with ggplot using:

ggplot(seasonality,aes(x=Date,y=seasonality$Laid Green))+geom_bar(stat="identity",width=1)

I get this:
enter image description here

I want to pool my data so that this is visually more pleasing, perhaps into 5 days? but I'm unsure how to do this. I am also trying to plot the green hatched on the same graph with nesting and hatching in 2 different colours.

Any help is appreciated!

r


Solution 1:[1]

You can use the package lubridate to round dates to a week start. dplyr from tidyverse can help you to then sum the counts.

library(lubridate)
library(tidyverse)

# so our random dataframes look the same
set.seed(123) 

# fake data
seasonality <- tibble(date = sample(seq(as.Date('2021-04-01'), as.Date('2021-06-01'), by="day"), 
                                    size = 100,
                                    replace = TRUE),
                      laid_green = sample(c(0:1),
                                          size = 100,
                                          replace = TRUE),
                      hatched_green = sample(c(0:1),
                                             size = 100,
                                             replace = TRUE)
                      ) %>% 
  arrange(date)

# plot
seasonality %>% 
  mutate(week = floor_date(date,
             unit = 'week')
  ) %>% 
  group_by(week) %>% 
  summarise(laid_green = sum(laid_green),
            hatched_green = sum(hatched_green)) %>% 
  pivot_longer(-week) %>% 
  ggplot(aes(x=week,y=value, fill = name)) +
  geom_col(pos = 'dodge')

plot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 seansteele