
###=================================================================###
###=================================================================###
###   OMDS Workshop: Exploring Your Data w/ggplot2 in R
###
###   by: Sarah Schwartz
###   date: 2-18-16
###=================================================================###
###=================================================================###

### ----------------- clear the global environment ---------------- ###

# remove a list of the complete listing so you start with a blank slate
rm(list = ls())


### --------------- load packages you expect to use --------------- ###

# For data wrangling  
library(plyr)          # split, apply, combine, arraange, mutate
library(dplyr)         # subset & join
library(tidyr)         # gather & spread
library(reshape2)      # melt & cast

# For plotting
library(ggplot2)       # the big guns!
library(ggthemes)      # more preset plotting themes
library(RColorBrewer)  # nice color pallettes

# Misc
library(MASS)          # includes the birthwt dataset
library(nlme)          # includes the Orthodont dataset

# http://www.r-bloggers.com/do-your-data-janitor-work-like-a-boss-with-dplyr/
# https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html 

### ------------------ set working directory -----------------------###

# this should be a FOLDER, not an specific file (unique for each project)
fp = file.path("C:/Users/A00315273/Box Sync", 
               "Office of Research Services",
               "OMDS",
               "OMDS Workshops",
               "OMDS ggplot2")

# set the wokring directory, where to get and save 'stuff'
setwd(fp)

# ask to "get" or show you the working directory
getwd()




### --------------------------------------------------------------- ###
### --------------------------------------------------------------- ###
###    SEVEN BASIC CONCEPTS of ggplot2
### --------------------------------------------------------------- ###
### --------------------------------------------------------------- ###

# "ggplot" the main function where you specify:
#       (a) your dataset
#       (b) aesthetics: variable mappings
#
# Geom = Geometrics includes: point, bar, density, line, area, ...
# Stat = Statistics include:
# Coord = Coordinate Systems: cartesian, polar, ...
#
# Scales: how to plot - continuous, discrete, log, ...
#
# Layer: add one thing at a time
# Facet: multiple panels
# Saving

help.search("geom_", package = "ggplot2")
help.search("stat_", package = "ggplot2")
help.search("coord", package = "ggplot2")
help.search("theme", package = "ggplot2")
help.search("scale", package = "ggplot2")






###--------------------------------------------------------------- ###
### ----------------- The Included MPG dataset  ------------------ ###
###--------------------------------------------------------------- ###

# this dataset is included in the ggplot2 package download

# type "mpg" into the help-tab's search-box to get the documentation
# see if the data is what you expected:

str(mpg)      # structure, compact display
dim(mpg)      # dimentions, # rows x # columns 
names(mpg)    # names of the variables
head(mpg)     # the first few rows (subjects or cases)



### --------- Always need to declare the data & mapping -----------###

# This just gives you a blank layer
p0 = ggplot(data = mpg,
            mapping = aes(x = cty,     # aes = "aesthetics"
                          y = hwy))

summary(p0)  # gives thehe summary

print(p0)     # creates the plot in the 'Plots' window 
p0            # does the same thing


### ------------------------ GEOM LAYER ---------------------------###

# This adds the points toothe blank layer (blank  grid)
p1 = p0 + geom_point()

summary(p1)
p1



# You can specify the COLOR and size of ALL the points...
p0 + geom_point(color= "red", size = 3)


# ...or you can use a VARIABLE to color the points
p2 = ggplot(data = mpg,
            mapping = aes(x = cty,
                          y = hwy,
                          color = factor(year))) +
    geom_point()

summary(p2)
p2


### ------------------------ STAT LAYER ---------------------------###

# You can add smoothed lines: 
#   "loess" = local partial polynomial regression

p1 + stat_smooth()    # smooths all the points
p2 + stat_smooth()    # smooths each group

p3 = p0 +
  geom_point(aes(color = factor(year))) +  # color the points ONLY
  stat_smooth()                            # leave the smoother on ALL

summary(p3)
p3




### ----------- Equivalent Ways to Create the Same Plot ---------- ###

### TWO steps 
p4 = ggplot(data = mpg,
            mapping = aes(x = cty,
                          y = hwy)) 
p4 + geom_point(aes( color = factor(year))) + stat_smooth()



### ONE step
p5 = ggplot(mpg) + 
       geom_point(aes(x = cty, y = hwy, color = factor(year))) +
       stat_smooth(aes(x = cty, y = hwy))

summary(p5)
p5



### ------------------------- SCALE LAYER ------------------------ ###

# Specify your OWN COLOR choices
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year))) +
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4"))  # color names

# Use another VARIABLE to specify the SIZE of the
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), size = displ)) +  # add size
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4"))




### -------------- Dealing with Over-Plotting -------------------- ###

# make the points TRANSPARENT to some degree
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), 
                 size = displ),
             alpha = 0.5) +               # 0 = clear vs. 1 = solid
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4"))


# move the points slightly aroung with JITTER
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), 
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4"))


# adjust the SIZE RANGE of the points 
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), 
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4")) +
  scale_size_continuous(range = c(4, 10))




### ------------------------- COORD LAYER ------------------------ ###

# FLIP the x and y axses 
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), 
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4")) +
  scale_size_continuous(range = c(4, 10)) +
  coord_flip()


# instead of rectangular, you could do a POLAR coordinate system...LOL
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), 
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4")) +
  scale_size_continuous(range = c(4, 10)) +
  coord_polar()


# more likely you many want to RESRICT the axis to ZOOOM
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = factor(year), 
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  stat_smooth(aes(x = cty, y = hwy)) +
  scale_color_manual(values = c("steelblue", "red4")) +
  scale_size_continuous(range = c(4, 10)) +
  coord_cartesian(xlim = c(15, 25), ylim = c(15, 40))



### ------------------------- FACET LAYER ------------------------ ###

# make a seperate PANEL based on a VARIABLE...
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = class,         # changed the color variable 
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  scale_size_continuous(range = c(4, 10)) +
  facet_grid(year ~ .)                         # ROWS by year

#  ...or by TWO variiables
ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = class,          
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  scale_size_continuous(range = c(4, 10)) +
  facet_grid(. ~ year)                         # COLUMNS by year



### --------------------- Add Labels & Titles -------------------- ###

ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = class,          
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  scale_size_continuous(range = c(2, 8)) +
  facet_grid(drv ~ year) +
  labs(x = "Driving Distance per Gallon on City Roads",   # x-axis
       y = "Driving Distance per Gallon on Highways",     # y-axis
       size = "Displacement",                        # legend for size
       color = "Model")                              # legend for color
  


### --------------------- Changing the Theme -------------------- ###

# store a plot to play with
p6 = ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point(aes(color = class,          
                 size = displ),
             alpha = 0.4,
             position = "jitter") +     
  scale_size_continuous(range = c(2, 8)) +
  facet_grid(. ~ year) +
  labs(x = "Driving Distance per Gallon on City Roads",   # x-axis
       y = "Driving Distance per Gallon on Highways",     # y-axis
       size = "Displacement",                        # legend for size
       color = "Model") 



# play around with default sets
p6 + theme_bw()    + scale_color_economist()             # I use this one most of the time
p6 + theme_classic()
p6 + theme_dark()
p6 + theme_light()
p6 + theme_linedraw()
p6 + theme_void()
p6 + theme_minimal()

# even more in another package
p6 + theme_economist()          # The Economist magazine
p6 + theme_economist_white()
p6 + theme_excel()              # NEVER use this one!
p6 + theme_few()
p6 + theme_gdocs()              # Google Docs
p6 + theme_solarized()
p6 + theme_stata()
p6 + theme_tufte()              # THE man in graphics
p6 + theme_wsj()                # The Wall STreet Journal

# there are also preset color scales you can explore
p6 + theme_economist() + scale_color_economist()


###--------------------------------------------------------------- ###
### ---------------- The Included DIAMOND dataset ---------------- ###
###--------------------------------------------------------------- ###

# Take a look at this dataset (from ggplot2)
str(diamonds)      # structure, compact display
dim(diamonds)      # dimentions, # rows x # columns 
names(diamonds)    # names of the variables
head(diamonds)     # the first few rows (subjects or cases)

# Declare the basics
p7 = ggplot(diamonds, aes(x = carat, y = price)) 

# All-defaut scatter plot
p7 + geom_point()

# change the size, transparency, and theme
p7 + geom_point(size = 0.1, alpha = 0.1) + theme_bw()


### ------------------------ STAT LAYER ---------------------------###

# instead of plotting EVERY point, make quare BINS of the values
p7 + stat_bin2d(bins = 70)

p7 + stat_density2d(aes(fill = ..level..),
                    geom = "polygon") +       # more flexible shapes
  coord_cartesian(xlim = c(0, 1.5),
                   ylim = c(-50, 6000))        # zoom out a bit 
                  





###--------------------------------------------------------------- ###
### --------------- The Included FAITHFUL dataset ---------------- ###
###--------------------------------------------------------------- ###

# Take a look at this dataset (from base R)
str(faithful)      # structure, compact display
dim(faithful)      # dimentions, # rows x # columns 
names(faithful)    # names of the variables
head(faithful)     # the first few rows (subjects or cases)


### -------------------------- HISTOGRAM ---------------------------###

# set the dataset
h = ggplot(faithful, aes(x = waiting)) 

# all defaults...
h + geom_histogram()

# change the BIN width
h + geom_histogram(binwidth = 30, 
                   color = "black") 
# play a bit more
h + geom_histogram(binwidth = 10, 
                   fill = "steelblue",
                   color = "black") 


###--------------------------------------------------------------- ###
### ---------------- The Included BIRTHWT dataset ---------------- ###
###--------------------------------------------------------------- ###

# Take a look at this dataset (from MASS)
str(birthwt)      # structure, compact display
dim(birthwt)      # dimentions, # rows x # columns 
names(birthwt)    # names of the variables
head(birthwt)     # the first few rows (subjects or cases)


### -------------------------- HISTOGRAM ---------------------------###

# Hisograms are good for one, continuous variable
ggplot(birthwt, aes(x = bwt)) + 
  geom_histogram(binwidth = 500, 
                 fill = "steelblue",
                 color = "black") 


ggplot(birthwt, aes(x = bwt)) + 
  geom_histogram(binwidth = 500, 
                 fill = "steelblue",
                 color = "black") +
  facet_grid(. ~ race)                  # panels side-by-side


ggplot(birthwt, aes(x = bwt)) + 
  geom_histogram(binwidth = 500, 
                 fill = "steelblue",
                 color = "black") +
  facet_grid(race ~ .)                 # panels stacked vertically


### -------------------------- BOX PLOT ----------------------------###

# these are my favorite for ANOVA type situations

# x is the grouping variable on which you want to compare...
# y is the continuous variable you are comparing
ggplot(birthwt, aes(x = factor(race), 
                    y = bwt)) + 
  geom_boxplot()

# have different boxes for every combination of smoking & race
ggplot(birthwt, aes(x = interaction(factor(race),
                                    factor(smoke)), 
                    y = bwt)) + 
  geom_boxplot()

# color by one of the variables
ggplot(birthwt, aes(x = factor(smoke), 
                    y = bwt,
                    fill = factor(race))) + 
  geom_boxplot()

# Could do the reverse
ggplot(birthwt, aes(x = factor(race), 
                    y = bwt,
                    fill = factor(smoke))) + 
  geom_boxplot() +
  theme_bw()



###--------------------------------------------------------------- ###
### ---------------- The provided CLIMATE dataset ---------------- ###
###--------------------------------------------------------------- ###

climate = read.csv("climate.csv", header = TRUE)

# Take a look at this dataset
str(climate)      # structure, compact display
dim(climate)      # dimentions, # rows x # columns 
names(climate)    # names of the variables
head(climate)     # the first few rows (subjects or cases)


### -------------------------- LINE PLOT ----------------------------###

# leave it to the defaults
ggplot(climate, aes(Year, Anomaly10y)) +
  geom_line()

# Draw dashed lines for confidence regions
ggplot(climate, aes(Year, Anomaly10y)) + 
  geom_line(size = 0.7, 
            color = "black") + 
  geom_line(aes(Year, Anomaly10y + Unc10y), 
            linetype = "dashed", 
            size = 0.7, 
            color = "red") + 
  geom_line(aes(Year, Anomaly10y - Unc10y), 
            linetype = "dashed", 
            size = 0.7, 
            color = "red") + 
  theme_gray()

# add a ribbon instead
ggplot(climate, aes(Year, Anomaly10y)) +
  geom_ribbon(aes(ymin = Anomaly10y - Unc10y,
                  ymax = Anomaly10y + Unc10y),
              fill = "blue", alpha = .1) +
  geom_line(color = "steelblue")




###--------------------------------------------------------------- ###
### ------------------ The Included IRIS dataset ----------------- ###
###--------------------------------------------------------------- ###

# Take a look at this dataset (from base R)
str(iris)      # structure, compact display
dim(iris)      # dimentions, # rows x # columns 
names(iris)    # names of the variables
head(iris)     # the first few rows (subjects or cases)


ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))

myplot = ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))
myplot + geom_point()



### -------------------------- BAR CHART ----------------------------###

# defaults
ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_bar(stat = "identity")

### ---------------------- STACKED BAR CHART ------------------------###

# first we have to change from wide to long format
df = melt(iris, id.vars = "Species")
head(df)

# then we can do it
ggplot(df, aes(x = Species, 
               y = value, 
               fill = variable)) +
  geom_bar(stat = "identity")

### ---------------------- SIDE-by-SIDE BAR CHART ------------------------###

ggplot(df, aes(x = Species, 
               y = value, 
               fill = variable)) +
  geom_bar(stat = "identity",
           position = "dodge")          # this forces the bar side-by-side


# RColorBrewer package has lots to choose from
display.brewer.all()

ggplot(df, aes(x = Species, 
               y = value, 
               fill = variable)) +
  geom_bar(stat = "identity",
           position = "dodge") +
  scale_fill_brewer(palette = "Set1")   # there are lots of nice combos


# compare to a box plot...
ggplot(df, aes(x = variable, 
               y = value, 
               fill = Species)) +
  geom_boxplot()





# Save a subset of only 1000 of the rows in the diamond dataset
d = diamonds[sample(1:nrow(diamonds), 1000), ]
head(d)

ggplot(d, aes(x = carat, y = price, color = color)) + geom_point()

ggplot(d, aes(x = clarity, fill = cut)) + 
  geom_bar(position = "dodge")


###--------------------------------------------------------------- ###
### ------------- The Included ORTHODONT dataset  ---------------- ###
###--------------------------------------------------------------- ###

# this dataset is included in the nlme package download

?Orthodont

str(Orthodont)      # structure, compact display
dim(Orthodont)      # dimentions, # rows x # columns 
names(Orthodont)    # names of the variables
head(Orthodont)     # the first few rows (subjects or cases)


ggplot(Orthodont,
       aes(x = age,
           y = distance,
           group = Subject,
           color = Sex)) +      # Color by gener
  geom_line()

ggplot(Orthodont,
       aes(x = age,
           y = distance,
           group = Subject)) +
  geom_line() +
  facet_grid(. ~ Sex)           # panels by gender




# http://www.ats.ucla.edu/STAT/r/faq/longitudinal.htm

### --------------------------------------------------------------- ###
### --------------------------------------------------------------- ###
###    SAVING YOUR PLOT
### --------------------------------------------------------------- ###
### --------------------------------------------------------------- ###

# If the plot is on your screen
ggsave("filename.png")


# if the plot is saved to "plot1"
ggsave(plot1, file = "~/path/to/figure/filename.png")


# you can set the size
ggsave(file = "/filename.png", 
       width = 6,
       height =4)


# you can use any format (pdf, png, svg, jpg)
ggsave(file = "filename.eps")
ggsave(file = "filename.jpg")
ggsave(file = "filename.pdf")



