How can I get an algebraic equation of a median curved line from ggplot in R?

47 views Asked by At

I have made a code that extracts multiple flood events (colored lines), clusters them (3 clusters) and plots them together in one picture. Additionally, I used the ggplot stat.summary command to visually find a median line (black) that represents a shape of the each group so I can compare them. This is the code that I used to get this plot:

df %>% ggplot(aes(
  x = flowDayShifted,
  y = flowScaled,
  group = interaction(clusterFourier, as.factor(peak_number)),
  colour = as.factor(year)
)) + geom_line() +
  facet_wrap(~ clusterFourier,  ncol = 3) +
  stat_summary(
    fun.y = "median",
    aes(group = clusterFourier),
    color = "black",
    geom = "line",
    size = 1.2
  )

enter image description here

Is there a possibility to get the algebraic equation of the each median line from the ggplot somehow? I do not know what rank is the line nor anything about it, I only see it visually.

Thank you!

I tried sth along these lines but did not get an actual equation. I do know the equation can be quite a mess but that does not matter if it is the correct representation.

# Extract information about the median line
median_layer <- ggplot_build(gg)$data[[length(ggplot_build(gg)$data)]]
# Fit a model to the median line data
median_model <- loess(y ~ x, data = median_layer, span = 0.75)  # You can adjust span as needed
# Print the summary of the fitted model
summary(median_model)
0

There are 0 answers