【问题标题】:How do I show Y value of highest density point on a violin plot with ggplot2?如何使用 ggplot2 在小提琴图上显示最高密度点的 Y 值?
【发布时间】:2019-01-04 03:11:39
【问题描述】:

让我们从 docs 的示例中获取 ggplot2 小提琴图的数据集,

> ToothGrowth$dose <- as.factor(ToothGrowth$dose)
> head(ToothGrowth)
   len supp dose
1  4.2   VC  0.5
2 11.5   VC  0.5
3  7.3   VC  0.5
4  5.8   VC  0.5
5  6.4   VC  0.5
6 10.0   VC  0.5

如果我们绘制图表,

library(ggplot2)
# Basic violin plot
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_violin()
p
# Rotate the violin plot
p + coord_flip()
# Set trim argument to FALSE
ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_violin(trim=FALSE)

我们得到了这个graph

如何显示峰值的数值,即 Y 轴上密度最高的点?

【问题讨论】:

    标签: r ggplot2 violin-plot


    【解决方案1】:

    你的意思是这样的吗?

    ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
        geom_violin(trim = FALSE) +
        geom_text(
            data = ToothGrowth %>%
                group_by(dose) %>%
                summarise(len = mean(len)),
            aes(x = as.factor(dose), y = len, label = len))
    


    更新

    要打印最大(密度)的位置,您可以执行以下操作

    ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
        geom_violin(trim = FALSE) +
        geom_text(
            data = ToothGrowth %>%
                group_by(dose) %>%
                nest() %>%
                transmute(dose, len = map_dbl(data, function(x) {
                    dens <- density(x$len)
                    dens$x[which.max(dens$y)] })),
            aes(x = as.factor(dose), y = len, label = sprintf("%4.3f", len)))
    

    【讨论】:

    • 没有。我认为您正在打印平均值。但我想要情节有峰值的值。所以在 0.5 的情况下,它应该略小于 10。
    • 使用内置摘要可能更容易,例如geom_text(aes(label = round(stat(y), 3)), stat = 'summary', fun.y = 'mean')。或者密度:geom_text(aes(label = round(stat(y), 3)), stat = 'summary', fun.y = function(x) { d &lt;- density(x); d$x[which.max(d$y)] })
    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2017-01-04
    • 2016-06-13
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多