我正在尝试向geom_density_ridge ggplot添加方法。我一直在研究一个非常类似的问题(Adding a mean to geom_density_ridges)。我可以为山脊生成平均值,但是它们放错了位置。我可以肯定的是,这是因为我对分组因子进行了重新排序,以使各个脊线都符合我想要的顺序,但是生成均值的代码使用了原始顺序。我尝试了几种重新排序方式的方法,但是运气不佳。
背景 具有数十万行的原始数据集包括以下内容
要获得从最低到最高绘制站点的图,我在ggplot语句中按-altitude对站点名称进行了重新排序。
我曾经尝试过将密度添加到density_lines小波上,但是我缺乏R的专业知识。.如何从数字中创建一个因子并将其传递到小波上?
代码
#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..