# Import packages ---------------------------------------------------------

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.3     ✓ purrr   0.3.4
## ✓ tibble  3.1.2     ✓ dplyr   1.0.6
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   1.4.0     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(here)
## here() starts at /home/daniele/Desktop/Bachelor/Stat/Assignments/SecondAssignment/stat_finalAssignment
library(janitor)
## 
## Attaching package: 'janitor'
## The following objects are masked from 'package:stats':
## 
##     chisq.test, fisher.test
# Import dataset and clean ----------------------------------------------------------

data <- read_csv(here('forPlot.csv'))
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   age = col_double(),
##   truesd = col_double(),
##   mean = col_double(),
##   iq_ord = col_character(),
##   iq = col_character()
## )
data.clean <- data %>%
    clean_names() %>% 
    group_by(age)

# Recreate plot

plt1 <-data.clean %>% ggplot(aes(x = factor(age), y = mean, fill = factor(iq_ord))) +
        geom_bar(stat = 'identity', 
             position = position_dodge(0.94)) +
        geom_errorbar(aes(ymin = mean - truesd, ymax = mean + truesd), colour = 'black', width = .1, position = position_dodge(.94)) +
        scale_y_continuous(breaks = seq(from = 0, to = 150, by = 10)) +
        scale_fill_discrete(labels = c('Low', 'Medium', 'High')) +
        labs(x = 'Age',
             y = 'Mean reading scores',
             title = 'mean reading scores of IQ groups across ages',
             fill = 'IQ level') +
        theme_minimal() +
        theme(plot.title = element_text(hjust = 0.5))

plt2 <- data.clean %>% ggplot(aes(x = factor(age), y = mean, fill = factor(iq_ord))) +
        geom_bar(stat = 'identity', 
                position = position_dodge(0.94)) +
        geom_errorbar(aes(ymin = mean - truesd, ymax = mean + truesd), colour = 'black', width = .1, position = position_dodge(.94)) +
        scale_y_continuous(breaks = seq(from = 0, to = 150, by = 10)) +
        scale_fill_discrete(labels = c('Low', 'Medium', 'High')) +
        labs(x = 'Age',
             y = 'Mean reading scores',
             title = 'mean reading scores across ages\ndivided by IQ',
             fill = 'IQ level') +
        theme_minimal() +
        theme(plot.title = element_text(hjust = 0.5)) +
        facet_grid(~factor(iq_ord, labels = c('Low IQ', 'Medium IQ', 'High IQ'))) +
        theme(legend.position = 'none')
plt1

plt2