ggplot2: Violin Plot with Stat="Identity"
Asked Answered
K

1

1

I'm trying to use ggplot to create a violin plot where instead of the widths of the violins being controlled by a density function, they directly represent the count of relevant elements.

I think this can be accomplished through setting geom_violin(stat="identity"), but R then complains

> ggplot(allData, aes(x = tool, y = length)) + geom_violin(stat="identity")
Warning: Ignoring unknown parameters: trim, scale
Error in eval(substitute(list(...)), `_data`, parent.frame()) : 
  object 'violinwidth' not found

Trying to add aes(violinwidth=0.2*count), as this answer suggests, gives

> ggplot(allData, aes(x = tool, y = length)) + geom_violin(stat="identity", aes(violinwidth=0.2*count))
Warning: Ignoring unknown parameters: trim, scale
Warning: Ignoring unknown aesthetics: violinwidth
Error in FUN(X[[i]], ...) : object 'count' not found

And while I can set violinwidth to just a constant, this makes the violins just rectangles. How can I fix this?

Kelcie answered 14/8, 2018 at 18:4 Comment(0)
T
2

When I run this with some sample data, it generates the plots ok with and without the changes to stat and violinwidth. Is your count a column in allData?

library(ggplot2)

dt <- data.frame(category = rep(letters[1:2], each = 10),
                 response = runif(20),
                 count = rpois(20, 5))

ggplot(dt, aes(x = category, y = response)) + geom_violin()

ggplot(dt, aes(x = category, y = response)) + 
  geom_violin(stat = "identity", aes(violinwidth = 0.1*count))
Thanatos answered 14/8, 2018 at 20:0 Comment(4)
Ah. It does not. I thought I could use count without having a count column, kinda like how you can do geom_violin(scale="count") and it calculates the counts for youKelcie
Yup, adding a count column fixed it.Kelcie
Ignoring unknown aesthetics: violinwidthIiette
Strange warning, it does seem to be controlling the width still e.g. if you change it to 0.2* it does growThanatos

© 2022 - 2025 — McMap. All rights reserved.