setwd("C:/Users/Jerome/Documents/Data_Science_110/Datasets")
library(ggplot2)
#Read data from csv file
data<-read.csv("lcn_mean_nutr_measure.csv")
#For some reason changing "dodge" to "dodge2" worked. Not sure what the
#difference is. Found one description at the beginning of https://ggplot2.tidyverse.org/reference/position_dodge.html
plot<-ggplot(data, aes(fill=Birth_Year, y=mean_nutr_measure, x=Svy_Year)) +
geom_bar(position="dodge2", stat="identity")
print(plot)

#Alternatively, changing the Birth_Year (which is treated as numerical) to a factor
#also works.
plot<-ggplot(data, aes(fill=as.factor(Birth_Year), y=mean_nutr_measure, x=as.factor(Svy_Year))) +
geom_bar(position="dodge", stat="identity")
print(plot)

#Fixing x-axis
#Change the x-axis to display ONLY 2007 and 2013, by changing Svy_Year from numerical
#to factor so that is it not treated as a quantitative/continuous variable but as two
#categories named 2007 and 2013
plot<-ggplot(data, aes(fill=Birth_Year, y=mean_nutr_measure, x=as.factor(Svy_Year))) +
geom_bar(position="dodge2", stat="identity")
print(plot)

#If we want to have the birth year labels under each column and not in the legend
#or above each bar it turns out to be nontrivial.
#This example looks pretty much exactly what we want:
#https://stackoverflow.com/questions/16279295/axis-labels-for-each-bar-and-each-group-in-bar-charts-with-dodged-groups
#So I am going to try it out.
#NOT FINISHED
#Only needs to be done once:
#install.packages("gridExtra")
#library(gridExtra)
#plot<-ggplot(data,aes(x=Svy_Year,y=mean_nutr_measure,fill=as.factor(Birth_Year))) +
# geom_bar(stat="identity",position="dodge") +
#scale_x_continuous("",breaks=(1:length(data$Birth_Year)+2007))labels=as.character(data$Birth_Year)+
#+theme(legend.position="none")
# theme(plot.margin = unit(c(1,2,3,1), "lines"))
# Now with functions annotation_custom() and textGrob() add labels Study 1, Study 2 under the plot setting x and y coordinates (negative coordinates for y puts labels under the plot).
#
# p1<-p+annotation_custom(grob=textGrob("Study 1"),
# xmin=0,xmax=0,ymin=-.2,ymax=-0.2)+
# annotation_custom(grob=textGrob("Study 2"),
# xmin=1,xmax=1,ymin=-.2,ymax=-0.2)+
# annotation_custom(grob=textGrob("Study 3"),
# xmin=2,xmax=2,ymin=-.2,ymax=-0.2)+
# annotation_custom(grob=textGrob("Study 4"),
# xmin=3,xmax=3,ymin=-.2,ymax=-0.2)
#print(plot)