Search code examples
rggplot2histogram

Plotting one sampling day of the dataset instead of all days together in a histogram in r


I am running into some problems with plotting a histogram.

The dataset is comprised of 4 Sampling days. During these four days prependicular distances to individuals were counted. But now i need to plot the frequency of the perpendicular distance of every individual per day into a histogram.

My dataset has all four samplings(days) in one excel sheet under each other. but now i need to seperate the data for each day so i can plot seperate histograms.

I was able to plot the histogram of the four days together with hist() and ggplot()

hist(WPTD2$Distance,
     xlab = 'Perpendicular Distance',
     ylab = 'Number of Observations',
     main = 'Sampling 1-4 Frequency of Observation per Perpendicular Distance (WP)',
     col = 'skyblue', 
     breaks = 20) 

and

ggplot(WPTD2, aes(x=Distance)) + 
  geom_histogram(binwidth = 5,boundary=0)

And this was no problem to do so but i can't seem to figure out how to plot only the data related to the specific Sampling day.

I have tried seperating the days into a factor with four levels with

WPTD2$Sampling <- as.factor(WPTD2$Date) which resulted in: Result Date -> Sampling

enter image description here

I also tried altering the dataset with:

WPTD2$Sampling <- ave(WPTD2$Date, WPTD2$`Transect nr.`, FUN = seq_along)

but this wielded no usable result.


Solution

  • using filter() function you can subset day and pass the filtered data to ggplot():

    library(tidyverse)
    WPTD2 %>% filter(Date==44915) %>% ggplot(aes(x=Distance)) + 
      geom_histogram(binwidth = 5,boundary=0)
    

    If the Date is factor, then try to place the Date in the quotes inside filter() function:

    WPTD2 %>% filter(Date=="44915") %>% ggplot(aes(x=Distance)) + 
          geom_histogram(binwidth = 5,boundary=0)
    

    enter image description here