Home > Mobile >  violin plot in R and values in X axis
violin plot in R and values in X axis

Time:04-29

I created these two violin plots in R, using:

install.packages("vioplot")
par(mfrow = c(1, 2))
vioplot::vioplot(HEL$Y,las=2,main="HEL$Y",col="deepskyblue",notch=TRUE)
vioplot::vioplot(ITA$Y,las=2,main="ITA$Y",col="aquamarine",notch=TRUE)

as a result I get the following. However, I don't know why in the X axis I get 1 and 2. How can I get rid of the 2?

Thanks for your help. enter image description here

CodePudding user response:

This mysterious behavior is due to the use of the argument "notch = TRUE". Example:

set.seed(456)
vioplot(rnorm(10), notch = TRUE)

Violin plot

My interpretation is that notch is not an argument of vioplot, so the function interprets it as data to add to the graph (see the little smudge at y = 1: that's where it wants to put the new data, since TRUE equals 1 when it is converted into a numeric).

To confirm that an unknown argument is interpreted as data to be plotted, here is a little experiment:

vioplot(rnorm(10), unknown_argument = rnorm(10))

And the result:

Other violin plot

CodePudding user response:

This is a ggplot2 solution in case you're interested.

library(ggplot2)
library(dplyr)

# Recreate similar data
HEL <- data.frame(Y = rnorm(50, 8, 3))
ITA <- data.frame(Y = rnorm(50, 9, 2))

# Join in a single dataframe and reshape to longer format
dat <- bind_rows(rename(HEL, hel_y = Y),
                 rename(ITA, ita_y = Y)) |>
  tidyr::pivot_longer(everything())

# Make the plots
dat |> 
  ggplot(aes(name, value))  
  geom_violin(aes(fill = name))  
  geom_boxplot(width = 0.1)  
  scale_fill_manual(values = c("deepskyblue", "aquamarine"))  
  theme(legend.position = "")

Created on 2022-04-28 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related