#if you do not have the packages yet
#install.packages("tidyverse") 
#install.packages("ggpubr")

library(tidyverse)
library(ggpubr)
data(iris)

# 1 and 2
plot_sepal <- ggplot(iris, mapping = 
      aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = 'lm', aes(fill = Species)) +
  scale_color_manual(values = c('tomato','steelblue', 'forestgreen')) +
  theme_bw()
plot_sepal

# 3
plot_petal_vs_sepal <- ggplot(iris, mapping = aes(x = Petal.Length/Petal.Width, 
                                                  y = Sepal.Length/Sepal.Width, 
                                                  color = Species)) +
  geom_point() +
  geom_smooth(method = 'lm', aes(fill = Species)) +
  scale_color_manual(values = c('tomato','steelblue', 'forestgreen')) +
  theme_bw() +
  theme(legend.position="none")

ggarrange(plot_sepal + theme(legend.position="none"), 
          plot_petal_vs_sepal, nrow = 1)

# 4
stats_sepal_widths <- iris %>% 
  group_by(Species) %>%
  summarise(mean = mean(Sepal.Width), sd = sd(Sepal.Width))

ggplot(stats_sepal_widths, mapping = aes(x = Species, y = mean, fill = Species)) + 
  geom_bar(stat = "identity") +
  geom_errorbar(aes(x = Species, ymin=mean-sd, ymax=mean+sd), 
                width=0.4, colour="grey", alpha=0.9, size=1.3) +
  coord_flip() +
  scale_fill_manual(values = c('tomato','steelblue', 'forestgreen')) +
  theme_bw()

# 5
library(ggpubr)
iris %>% mutate(species_plot = forcats::fct_recode(as.factor(Species), 
                                                   Setosa = "setosa", 
                                                   Virginica = "virginica", 
                                                   Versicolor = "versicolor")) %>% 
  ggplot(aes(x = species_plot, y = Petal.Length, fill = species_plot)) + 
  geom_boxplot() + 
  stat_compare_means(label.y = 9.5) + 
  stat_compare_means(comparisons = list(c('Setosa', 'Versicolor'), 
                                        c('Versicolor','Virginica'), 
                                        c('Setosa', 'Virginica'))) + 
  scale_fill_manual(values = c('tomato','steelblue', 'forestgreen')) + 
  theme_bw() + 
  xlab('') + ylab('Petal length [cm]') + 
  theme(legend.position = 'none')

# or simpler version
my_comp <- list(c('setosa', 'versicolor'), 
                c('versicolor','virginica'), 
                c('setosa', 'virginica'))
ggplot(iris, aes(x = Species, y = Petal.Length, fill = Species)) + 
  geom_boxplot() + 
  stat_compare_means(label.y = 9.5) + 
  stat_compare_means(comparisons = my_comp)

# bonus
stats_iris <- iris %>%
  map_df(~ tibble(
    mean = if (is.numeric(.x)) mean(.x) else NA,
    distinct = n_distinct(.x)
  ))
