R violin plot (vioplot) does not display data of same value

871 views Asked by At

I am trying to create a violin plot of results of a survey, and everything looks fine, expect for those cases where all respondents submitted the same answer. In these cases, vioplot displays nothing, and I changed from vioplot to boxplot to have at least a line where the answers are.

My code:

plot(1,1,xlim=c(0,10),ylim=range(c(x1,x2,x3,x4,x5,x6,x7,x8,x9)),type="n",
 xlab="",ylab="",axes=FALSE)
axis(side = 1, at=2,label="")
axis(side = 1, at=5,label="")
axis(side = 1, at=8,label="")

axis(side=2)
vioplot(x1,at=1,col="blue",add=TRUE)
vioplot(x2,at=2,col="red",add=TRUE)
vioplot(x3,at=3,col="yellow",add=TRUE)
vioplot(x4,at=4,col="blue",add=TRUE)
vioplot(x5,at=5,col="red",add=TRUE)
vioplot(x6,at=6,col="yellow",add=TRUE)
boxplot(x7,at=7,col="blue", add=TRUE)
boxplot(x8,at=8,col="red",add=TRUE)
vioplot(x9,at=9,col="yellow",add=TRUE)

This is what it looks like with boxplot, using vioplot instead, the whole column is empty.

enter image description here

Any ideas what I am doing wrong and what the code should be like so that I can use a vioplot?

1

There are 1 answers

1
Jonny Phelps On BEST ANSWER

Had a quick play with the package. There aren't many options, doesn't look like it handles these cases well. You could try jitter on the data to create some small random noise for the graph e.g.

library(data.table)
library(vioplot)

cdt <- setDT(copy(cars))
cdt[, new := 16]

vioplot(cdt$speed, cdt$dist, jitter(cdt$new, 0.0001))

My preferable suggestion is to try out geom_violin in ggplot2 package.

http://www.sthda.com/english/wiki/ggplot2-violin-plot-quick-start-guide-r-software-and-data-visualization

Prettier and more functional :)

p.s. sorry if you don't use data.table; I don't code out of it now :)