2
votes

I try to plot a violin plot with the R package ggplot2 with the code

norm2 = function(v) return(sqrt(sum(v*v)))
myfct = function(d) {
  vec_length = Inf
  while (vec_length > 1){
    vec_length = norm2(runif(n=d,min=-1,max=1))
  }
  return(vec_length)
}

df = data.frame(x = rep.int(1:5, 2))
df$vec_length = sapply(df$x, myfct)
ggplot(df, aes(factor(x),vec_length)) + geom_violin(trim=FALSE)

but I get

Warning:
In max(data$density) :
  no non-missing argument for max; return -Inf

And my plot is

enter image description here

What have I done wrong?

1
norm2 is a package not a function? Using base::norm throws an error - Fons MA
@FonsMA: Sorry, added the function. - Make42
@RLave: Sorry, added the function. - Make42

1 Answers

2
votes

Your data only has two vec_length (y) for each x. This is rather a "special case" where the violin would reduce into a line. One could have implemented geom_violin() also as geom_line() in such cases, but that isn't realized like that:

library(ggplot2)
ggplot(df1, aes(factor(x), vec_length)) + geom_line()

enter image description here

To draw a violin you need at least three y values:

df2 <- data.frame(x=rep.int(1:5, 3))
df2$vec_length <- sapply(df2$x, myfct)
ggplot(df2, aes(factor(x), vec_length)) + geom_violin(trim=FALSE)

enter image description here


data

library("SpatioTemporal")
set.seed(42)
myfct <- function(d) {
  vec_length <- Inf
  while (vec_length > 1){
    vec_length <- norm2(runif(n=d, min=- 1, max=1))
  }
  return(vec_length)
}

df1 <- data.frame(x=rep.int(1:5, 2))
df1$vec_length <- sapply(df1$x, myfct)