3

Let's take the dataset from docs' example for ggplot2 violin graphs,

> 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

And if we plot the graph,

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)

we get this graph.

How do I show the numeric value of the peak, i.e the point with highest density on Y axis?

mlemboy
  • 95
  • 2
  • 6

1 Answers1

2

Do you mean something like this?

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


Update

To print the position of max(density) you could do the following

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

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • 1
    No. I think you are printing the mean. But I want the value where the plot has the peaks. So in 0.5's case it should be little bit less than 10. – mlemboy Jul 27 '18 at 04:10
  • Using the built-in summaries can be easier, e.g. `geom_text(aes(label = round(stat(y), 3)), stat = 'summary', fun.y = 'mean')`. Or for the density: `geom_text(aes(label = round(stat(y), 3)), stat = 'summary', fun.y = function(x) { d <- density(x); d$x[which.max(d$y)] })` – Axeman Jul 27 '18 at 11:40