-1
library(ggplot2)

ggplot(mtcars, aes(cyl, mpg, fill = factor(cyl))) +
  geom_violin(alpha = 0.66, color = NA, position = position_dodge(1), width = 1) +
  geom_boxplot(color = "black", alpha = 0.9, width = 0.4, position = position_dodge(1)) +
  scale_fill_brewer(palette = "Pastel2") +
  theme_bw() +
  scale_y_continuous(breaks = c(10, 15, 20, 25, 30, 35)) +
  theme(legend.position = c(0.9, 0.9)) + 
  theme(text = element_text(size = 12)) +
  labs(title = "Example", x = "Cyl", y = "MPG", fill = "CYL")

I don’t want the tip of my violin plot to be cut off. How can I make my plot similar to the plot shown below?

example

M--
  • 25,431
  • 8
  • 61
  • 93
  • 3
    Welcome to SO! It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. Please do not post an image of code/data/errors [for these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). Just include the code, console output, or data (e.g., dput(head(x)) or data.frame(...)) directly. – stefan May 11 '23 at 19:38
  • 2
    @user21830397, welcome to SO! You've been participating for a week, both questions have included requests to improve the quality of your questions. Please please please take a moment to read the links the stefan provided, they are not for "no reason", it really helps us to help you when we have more direct access and non-blurred images of code. I _suspect_ that questions with nothing but images for code/data get fewer looks by those who might help you. – r2evans May 11 '23 at 19:44
  • 1
    Welcome to Stack Overflow! Please don't post a picture of your dataset or code. In reference to to [Why should I not upload images of code, data, or errors?](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors) You need to provide a [minimal, reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – M-- May 11 '23 at 20:31

1 Answers1

2

To avoid the violins from being cut off set trim=FALSE in geom_violin.

library(ggplot2)

ggplot(mtcars, aes(cyl, mpg, fill = factor(cyl))) +
  geom_violin(alpha = 0.66, color = NA, position = position_dodge(1), width = 1, trim = FALSE) +
  geom_boxplot(color = "black", alpha = 0.9, width = 0.4, position = position_dodge(1)) +
  scale_fill_brewer(palette = "Pastel2") +
  theme_bw() +
  scale_y_continuous(breaks = c(10, 15, 20, 25, 30, 35)) +
  theme(legend.position = c(0.9, 0.9)) + 
  theme(text = element_text(size = 12)) +
  labs(title = "Example", x = "Cyl", y = "MPG", fill = "CYL")

stefan
  • 90,330
  • 6
  • 25
  • 51