1

I'm trying to show my data as a violin plot with an overlaid boxplot. I have four groups, split by two independent factors, so I put in the commands below.

The table has X1, Category, and Area columns.

ggplot(malbdata,aes(x=X1,y=Area,fill=Category))+  
       geom_violin()+
       geom_boxplot(width=.1)

And what I get is the graph attached, where it places the boxplots next to the violins, but not within them. I'm very new to working with R; any ideas on what might be going wrong? violin plot with boxplots

Dave2e
  • 22,192
  • 18
  • 42
  • 50
caspace37
  • 11
  • 1

1 Answers1

1

I believe the issue is the width = 0.1 parameter, e.g.

library(tidyverse)
library(palmerpenguins)

penguins %>% 
  na.omit() %>%
  select(species, island, bill_length_mm) %>% 
  ggplot(aes(x = island, y = bill_length_mm, fill = species)) +
  geom_boxplot(width=.1) +
  geom_violin()

example_1.png

If you make the widths the same they line up as expected:

library(tidyverse)
library(palmerpenguins)

penguins %>% 
  na.omit() %>%
  select(species, island, bill_length_mm) %>% 
  ggplot(aes(x = island, y = bill_length_mm, fill = species)) +
  geom_boxplot(width=.2) +
  geom_violin(width=.2)

example_2.png

Also, instead of using boxplots and violins (both of illustrating the distribution of values) it might be better to plot the individual values and the distribution, e.g.

library(tidyverse)
library(palmerpenguins)
library(ggbeeswarm)

penguins %>% 
  na.omit() %>%
  select(species, island, bill_length_mm) %>%
  rename(Species = species, Island = island) %>% 
  ggplot(aes(x = Island, y = bill_length_mm, fill = Species)) +
  geom_boxplot(width=.4, outlier.shape = NA,
               position = position_dodge2(preserve = "single")) +
  geom_quasirandom(aes(colour = Species), groupOnX = TRUE,
                   width=.2, alpha = 0.5, dodge.width = 0.4) +
  theme_bw(base_size = 16) +
  ylab("Bill Length (mm)")

example_3.png

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46