Density curve for grouped observations

88 Views Asked by At

I have a data set where I have hourly observations of different species. For each hour, all the observations are pooled for each species and this was done for 24 hours. Following is a part of the dataframe:

Hr  Sp1 Sp2 Sp3 Sp4 Sp5
1   8   25  1   7   7
2   3   14  0   50  4
3   5   25  1   4   10
4   7   26  1   4   11
5   5   19  0   7   11

I want to plot a density curve for observations of each species against time. Hence, I have 24 continuous groups (0100 hr, 0200 hr....2400 hr) starting from 0000 hr as x-axis, y axis is the counts or observations for each hour over 24 hour for each species. Please suggest how can I do that in R? I also want all species density curves in one plot. How do I do that?

Thanks a lot!

1

There are 1 best solutions below

1
On
library(reshape2)
library(ggplot2)

dt <- data.frame(Hr = 1:5,
                 Sp1 = c(8, 3, 5, 7, 5),
                 Sp2 = c(25, 14, 25, 26, 19),
                 Sp3 = c(1, 0, 1, 1, 0),
                 Sp4 = c(7, 50, 4, 4, 7),
                 Sp5 = c(7, 4, 10, 11, 11))

data <- melt(dt, id = c("Hr"))
data <- data.frame(Hr = rep(data$Hr, data$value),
                   variable = rep(data$variable, data$value))

ggplot(data, aes(Hr, colour = variable)) + geom_density()

enter image description here

http://ggplot2.tidyverse.org/reference/geom_density.html