0

I don't know how to align the dots to each belong to it is box plot. Why they are appearing like that?

I found this post, but it is answering the dodging part which is not part of my code

here is my code

library(phyloseq)
library(ggplot2)

plot_richness(ps.prev.intesParts.f, x = "part", measures = "Shannon", 
              color = "Samples") +
  geom_boxplot() +
  theme_classic() +
  theme(text = element_text(size = 20),
        strip.background = element_blank(),
        axis.text.x.bottom = element_text(angle = 90),
        legend.title = element_blank())) +
  labs(x = "Intestinal Parts", y = "Shannon Index")

Could you please advise?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Your problem is that dodging isn't part of your code. The way the boxplots are next to each other even though they share the same x-values is called "dodging". You need to dodge the points in the same was as the boxplots are dodged automatically. The answer at your link looks like a very good start, if not a full solution. – Gregor Thomas Aug 30 '22 at 18:29
  • If you can share some reproducible data using `dput`, so we can help you better. – Quinten Aug 30 '22 at 18:40

1 Answers1

0

You are correct that you need to specify dodging. However, dodging needs to be set in the underlying geom_point(...) of the plot_richness function itself. Unfortunately, phyloseq offers no such option. This means you'll need to calculate the alpha diversity measures yourself and generate your own plot. Luckily this only requires a few extra lines of code. Here's an example using phyloseq's GlobalPatterns.

require("phyloseq")
require("dplyr")
require("ggplot2")

# Load data
data("GlobalPatterns")

# Calculate alpha indices
a_div <- estimate_richness(GlobalPatterns, measures = "Shannon")
a_div$SampleID <- row.names(a_div)

# Add sample_data from physeq object
a_div <- left_join(a_div, 
                   sample_data(GlobalPatterns), 
                   by = c("SampleID" = "X.SampleID"))

# GlobalPatterns only has grouping by SampleType. 
# Generate an extra group by duplicating all rows
a_div <- rbind(a_div, a_div)
a_div$Samples <- rep(x = c("MMV", "VMV"), 
                     each = nrow(a_div)/2)

# Plot
ggplot(a_div,
       aes(x = SampleType,
           y = Shannon,
           colour = Samples)) +
  geom_boxplot(position = position_dodge(width = 0.9)) +
  geom_point(position = position_dodge(width = 0.9)) +
  theme_classic() +
  theme(text = element_text(size = 20),
        strip.background = element_blank(),
        axis.text.x.bottom = element_text(angle = 90,
                                          hjust = 1,
                                          vjust = 0.5),
        legend.title = element_blank())

Created on 2022-09-02 by the reprex package (v2.0.1)

gmt
  • 325
  • 1
  • 7