I'm am trying to add means to a geom_density_ridge
ggplot. I've been working off a very similar question (Adding a mean to geom_density_ridges). I can generate means for my ridges, but they are misplaced. I'm pretty certain that this is because I reorder my grouping factor to get the individual ridges into the order I want, but the code that generates the means uses the original order. I've tried several ways to reorder the means, but I'm having little luck.
Background The original dataset with a few hundred thousand rows includes the following
- SiteNames - a factor with 12 levels
- value - a numeric with temperature data ranging from about -20 to 40
- altitude - numeric with 12 possible values which are unique to each factor level in SiteNames (e.g. Arboretum Meadow is always 2200 )
To get the plot to draw the Sites from lowest to highest, I reorder SiteNames by -altitude in the ggplot statement.
I've tried adding altitude to the density_lines tibble, but my lack of R expertise is showing.. How can one create a factor from a numeric and pass it through to the tibble?
CODE
#Add means to ridgeline plot
#generate density_ride plot
Fig1 <- ggplot(tempsVertSortedAltitude,
aes(x=value,y=reorder(SiteNames, -altitude), fill=..x..))+
geom_density_ridges_gradient(rel_min_height = 0.01)+scale_x_continuous(expand = c(0.01, 0)) +
scale_y_discrete(expand = c(0.01, 0)) +
scale_fill_viridis(name = "Temp. [°C]", option = "C") +
labs(title = 'Hourly Mean Temperatures at SEGA Sites') +
theme_ridges(font_size = 13, grid = TRUE) + theme(axis.title.y = element_blank())
# create mean lines
density_lines <-
tempsVertSortedAltitude %>%
**fct_reorder(SiteNames, -altitude) %>%** # code added to reorder SiteNames levels (lowest to highest)
group_by(SiteNames) %>%
summarise(x_mean = mean(value, na.rm = TRUE ), alt = -altitude) %>%
mutate(group = as.integer(SiteNames)) %>%
left_join(ggplot_build(Fig1) %>% purrr::pluck("data", 1),
on = "group") %>%
group_by(group) %>%
summarise(x_mean = first(x_mean),
density = approx(x, density, first(x_mean))$y,
scale = first(scale),
iscale = first(iscale), alt = alt)
# add segments and plot
Fig1 +
geom_segment(aes(x = x_mean,
y = group,
xend = x_mean,
yend = group + density * scale * iscale),
data = density_lines)
Here is the plot with the the sites in the correct order, but the means misplaced..
Here is a version with the reorder removed, so the sites are in alphabetical order, and the means seem reasonable..