How to add a smooth line in a graph

Hello folks,
I have a question for the following diagram.
I would like to put a line over the bars that softly shows a "trend" or "average".
Unfortunately, I don't know exactly how it works.
This is the code I used.
The diagram shows the activity of animals photographed with a camera trap.

If I use geom_line(), the diagram only shows the maximum number of animals in a picture (which is 2). But I need the total number added up - like the bars.
With geom_smooth() a mean value is formed, which is unfortunately unusable.

Could you please help me with that?

ggplot(SIGS)+
  geom_col(aes(x = Photo.time@hour + Photo.time@minute/60, y = Number.of.Animals)) + ylab("Animals") +
  scale_x_continuous(breaks = seq(0,24,4), name = "Uhrzeit", labels = c( "0:00", "4:00", "8:00", "12:00", "16:00", "20:00", "23:59")) +
  theme_bw() + theme_classic()

See the FAQ: How to do a minimal reproducible example reprex for beginners. Not sure what the bar represents—cumulative captures?

Is SIGS an R dataset in a package? Or your own dataset? We can't reproduce your issue without the data so we either need a reprex that gives us a SIGS dataset or a require/library line to load the package that has SIGS in it.

It appears you have a dataset with number of animals and time data.

But you have not shown us the geom_line command that "fails"

But you also have defined a new statistical method... The softly trend.

I suspect what you mean is a rolling average.

zoo::roll_mean( ). Would be a sensible approach say using 5 minutes

So something like

require(dplyr)
require(zoo)
SIGS %>%
mutate(rolling, roll_mean(. , k = 5) %>%
ggplot() %>%
Blah blah

Would be a good approach.

Also I suspect you should move the aes(...) section to the ggplot(...), So you only tell geom_line(aes(y=rolling)) as it knows the x already.

rolling will give some warnings when plotted as you get some NA values at the start/end of your data when there is not 5 data points to average

More work may be needed depending how the data looks which is why a reprex would help

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.