iskandarblue
iskandarblue

Reputation: 7526

Adjusting grid and tick marks on violin plot produced by vioplot package

The following code will display a vioplot overlaid with a grid

dat <- sample(1:5, 100, replace = TRUE)
vioplot(dat, col = "yellow")
grid (NULL, lty = 6, col = "grey") 

enter image description here

How would one remove the x-axis label of "1", its corresponding tick mark, and only display horizontal grid lines?

Adding the following does not work:

title(xlab="")

Upvotes: 1

Views: 1137

Answers (1)

eipi10
eipi10

Reputation: 93881

You can remove the x-axis tick label and draw only horizontal gridlines as follows:

library(vioplot)

set.seed(2)
dat <- sample(1:5, 100, replace = TRUE)

# Draw plot without x-axis tick label
vioplot(dat, col = "yellow", names="")

# Draw only horizontal grid lines
grid(NULL, lty = 6, col = "grey", nx=0)

It looks like the axis tick marks are hard-coded. However, you can modify the vioplot function itself to create an option to remove the tick marks. To get the function code, type vioplot in the console. Copy and paste the code into an R script and assign the function a new name, like my_violin. Somewhere inside vioplot/my_violin there's a call to the axis function to draw the x-axis. We just need to add a way to modify this call to axis so that we can decide whether or not to draw tick marks. To do that, add the following argument to the my_violin function declaration:

tick=TRUE

Then find the following line of code inside the my_violin function:

axis(1, at = at, label = label)

and change it to this:

axis(1, at = at, label = label, tick=tick)

Now, run the new function with tick=FALSE:

my_violin(dat, col = "yellow", names="", tick=FALSE)
grid(NULL, lty = 6, col = "grey", nx=0)

enter image description here

Here's a ggplot2 approach to the same plot:

library(ggplot2)

ggplot(dat=data.frame(y=dat), aes(x="", y=y)) +
  geom_violin(fill="yellow") + 
  geom_hline(yintercept=1:5, colour="grey40", linetype=4, size=0.3) +
  geom_boxplot(width=0.05) +
  theme_classic() +
  theme(axis.ticks.x=element_blank()) +
  labs(x="", y="")

enter image description here

Upvotes: 2

Related Questions