在geom_density_ridges上画线 [英] draw line on geom_density_ridges

查看:155
本文介绍了在geom_density_ridges上画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过ggridges的密度图画一条线

I am trying to draw a line through the density plots from ggridges

library(ggplot2)
library(ggridges)
ggplot(iris, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(rel_min_height = 0.01)

指示最高点,并在该点标记x的值.下面是这样的.任何有关完成此操作的建议都将受到赞赏

Indicating the highest point and label the value of x at that point. Something like this below. Any suggestions on accomplishing this is much appreciated

推荐答案

一种简洁的方法是询问ggplot对象本身,并使用它来构建其他功能:

One neat approach is to interrogate the ggplot object itself and use it to construct additional features:

# This is the OP chart
library(ggplot2)
library(ggridges)
gr <- ggplot(iris, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(rel_min_height = 0.01)  

缩短了下一部分,使用purrr::pluck提取了列表的整个data部分,而不是手动指定以后需要的列.

This next part has been shortened, using purrr::pluck to extract the whole data part of the list, instead of manually specifying the columns we'd need later.

# Extract the data ggplot used to prepare the figure.
#   purrr::pluck is grabbing the "data" list from the list that
#   ggplot_build creates, and then extracting the first element of that list.
ingredients <- ggplot_build(gr) %>% purrr::pluck("data", 1)

# Pick the highest point. Could easily add quantiles or other features here.
density_lines <- ingredients %>%
  group_by(group) %>% filter(density == max(density)) %>% ungroup()

# Use the highest point to add more geoms
ggplot(iris, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(rel_min_height = 0.01) +
  geom_segment(data = density_lines, 
               aes(x = x, y = ymin, xend = x, 
                   yend = ymin+density*scale*iscale)) +
  geom_text(data = density_lines, 
            aes(x = x, y = ymin + 0.5 *(density*scale*iscale),
                label = round(x, 2)),
            hjust = -0.2) 

这篇关于在geom_density_ridges上画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆