如何使用ggplot2在小提琴图上显示最高密度点的Y值?

时间:2018-07-27 03:37:16

标签: r ggplot2 violin-plot

让我们从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轴上密度最高的点?

1 个答案:

答案 0 :(得分:2)

你的意思是这样吗?

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))

enter image description here


更新

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

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)))

enter image description here