ggplot2: Violin Plot with Stat=“Identity”

2019-05-31 05:28发布

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?

1条回答
爷、活的狠高调
2楼-- · 2019-05-31 06:00

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))
查看更多
登录 后发表回答