Incorporating interactivity with the plotly R package

March 26, 2021 • PD Schloss • 3 min read

Output

Code

This is where we started before the episode

library(tidyverse)
library(readxl)

nmds <- read_tsv(file="raw_data/schubert.braycurtis.nmds_2d.axes")
metadata <- read_excel(path="raw_data/schubert.metadata.xlsx")
metadata_nmds <- inner_join(metadata, nmds, by=c('sample_id'='group')) %>%
  mutate(disease_stat = factor(disease_stat,
                               levels=c("DiarrhealControl",
                                        "Case",
                                        "NonDiarrhealControl")
                               )
         )

ggplot(metadata_nmds, aes(x=axis1, y=axis2, color=disease_stat, fill=disease_stat)) +
  stat_ellipse(geom="polygon", level=0.75, alpha=0.2, show.legend=FALSE) +
  geom_point() +
  coord_cartesian(xlim=c(-0.8, 0.8), ylim=c(-0.8, 0.8)) +
  labs(x="NMDS Axis 1",
       y="MNDS Axis 2") +
  scale_color_manual(name=NULL,
                     breaks=c("NonDiarrhealControl",
                              "DiarrhealControl",
                              "Case"),
                     values=c("gray", "blue", "red"),
                     labels=c("Healthy",
                              "Diarrhea",
                              "C. difficile positive")
  )+
  scale_fill_manual(name=NULL,
                     breaks=c("NonDiarrhealControl",
                              "DiarrhealControl",
                              "Case"),
                     values=c("lightgray", "dodgerblue", "pink"),
                     labels=c("Healthy",
                              "Diarrhea",
                              "C. difficile positive")
  )+
  theme_classic() +
  theme(
    legend.key.size = unit(0.25, "cm"),
    legend.position = c(0.95, 0.95),
    legend.background = element_rect(fill="white",
                                     color="black"),
    legend.margin = margin(t=-2, r=3, b=3, l=3),
    plot.margin = margin(t=1, r=3, b=1, l=1, unit="lines")
  )

ggsave("schubert_nmds_ellipse.tiff", width=5, height=4)

Installations