GGplot Customization Demo

Instructions

Submission:

Part-1: ggplot fundamentals review

In this part of the assignment, we will build up a figure piece by piece, to demonstrate the grammar of graphics.

Set environment

renv::restore()

Load library and data


# LOAD LIBRARY 
library(ggplot2)

# LOAD DATA
data("midwest", package = "ggplot2")  # load the data

#EXPLORE DATA: DATA COMES IN AS A TIBBLE  
head(midwest)
A tibble: 6 x 28
PID county state area poptotal popdensity popwhite popblack popamerindian popasian ... percollege percprof poppovertyknown percpovertyknown percbelowpoverty percchildbelowpovert percadultpoverty percelderlypoverty inmetro category
<int> <chr> <chr> <dbl> <int> <dbl> <int> <int> <int> <int> ... <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <int> <chr>
561 ADAMS IL 0.052 66090 1270.9615 63917 1702 98 249 ... 19.63139 4.355859 63628 96.27478 13.151443 18.01172 11.009776 12.443812 0 AAR
562 ALEXANDER IL 0.014 10626 759.0000 7054 3496 19 48 ... 11.24331 2.870315 10529 99.08714 32.244278 45.82651 27.385647 25.228976 0 LHR
563 BOND IL 0.022 14991 681.4091 14477 429 35 16 ... 17.03382 4.488572 14235 94.95697 12.068844 14.03606 10.852090 12.697410 0 AAR
564 BOONE IL 0.017 30806 1812.1176 29344 127 46 150 ... 17.27895 4.197800 30337 98.47757 7.209019 11.17954 5.536013 6.217047 1 ALU
565 BROWN IL 0.018 5836 324.2222 5264 547 14 5 ... 14.47600 3.367680 4815 82.50514 13.520249 13.02289 11.143211 19.200000 0 AAR
566 BUREAU IL 0.050 35688 713.7600 35157 50 65 195 ... 18.90462 3.275891 35107 98.37200 10.399635 14.15882 8.179287 11.008586 0 AAR

Initialize a blank canvas


g <- ggplot(midwest) 
plot(g) 

Customize canvas


g <- ggplot(midwest)+theme(panel.background = element_rect(fill = 'lightblue', color = 'purple'))
plot(g) 

Add coordinate system


# aes=Aesthetic mappings describe how variables in the data 
# are mapped to visual properties (aesthetics) of geoms.
g <- ggplot(midwest, aes(x=area, y=poptotal)) 
plot(g)

Customize the coordinate system

# aes=Aesthetic mappings describe how variables in the data 
# are mapped to visual properties (aesthetics) of geoms.
g <- ggplot(midwest, aes(x=area, y=poptotal)) 
g <- g + theme(panel.background = element_rect(fill = 'lightblue', color = 'purple'),
          panel.grid.major = element_line(color = 'red', linetype = 'dotted'),
          panel.grid.minor = element_line(color = 'green', linewidth = 2))
plot(g)

Add some points

#SCATTER PLOT-1
# aes=Aesthetic mappings describe how variables in the data 
# are mapped to visual properties (aesthetics) of geoms.
g <- ggplot(midwest, aes(x=area, y=poptotal)) + #TELL IT WHAT TO PLOT
geom_point()                                    #DO SCATTER PLOT
plot(g)                                         #GENERATE PLOT

Alternative method

#SCATTER PLOT-1 (ALT METHOD)
g <- ggplot(midwest, aes(x=area, y=poptotal))   #TELL IT WHAT TO PLOT
g <- g+geom_point()                             #TELL IT TO DO SCATTER PLOT
plot(g)                                         #GENERATE PLOT

Add context with labels

#SCATTER PLOT-1 (ALT METHOD)
g <- ggplot(midwest, aes(x=area, y=poptotal))   #TELL IT WHAT TO PLOT
g <- g+geom_point()+                             #TELL IT TO DO SCATTER PLOT
labs(title="Area Vs Population",                   #SET LABELS
    subtitle="From midwest dataset",
    y="Population (count)",
    x="Area (square miles)",
    caption="Midwest Demographics")
plot(g)                                         #GENERATE PLOT

Visualize the trend

g <- ggplot(midwest, aes(x=area, y=poptotal)) + #TELL IT WHAT TO PLOT
geom_point() +                             #TELL IT TO DO SCATTER PLOT
labs(title="Area Vs Population",                   #SET LABELS
    subtitle="From midwest dataset",
    y="Population (count)",
    x="Area (square miles)",  
    caption="Midwest Demographics") +                                  #DO SCATTER PLOT
# set se=FALSE to turnoff confidence bands
geom_smooth(method="lm")                        #ADD LINEAR BEST FIT LINE
plot(g)                                         #GENERATE PLOT

Change axis limits

#ADJUST AXIS LIMITS: (ZOOM IN)
#DOESN"T EFFECT POINTS OUTSIDE LIMITS OR THE TREND-LINE
g <- ggplot(midwest, aes(x=area, y=poptotal))+     #TELL IT WHAT TO PLOT
geom_point() +                                     #DO SCATTER PLOT
geom_smooth(method="lm")+                          #ADD LINEAR BEST FIT LINE
coord_cartesian(xlim=c(0,0.1), ylim=c(0, 200000))+ #SET LIMITS
labs(title="Area Vs Population",                   #SET LABELS
subtitle="From midwest dataset",
y="Population (count)",
x="Area (square miles)",
caption="Midwest Demographics")
plot(g)                                            #GENERATE PLOT

Lets explore some color

#POINT SIZE AND COLOR
g <- ggplot(midwest, aes(x=area, y=poptotal))+     #TELL IT WHAT TO PLOT
geom_point(col="steelblue", size=3) +              #DO SCATTER PLOT
geom_smooth(method="lm", col="firebrick")+         #ADD LINEAR BEST FIT LINE
coord_cartesian(xlim=c(0,0.1), ylim=c(0, 200000))+ #SET LIMITS
labs(title="Area Vs Population",                   #SET LABELS
subtitle="From midwest dataset",
y="Population (count)",
x="Area (square miles)",
caption="Midwest Demographics")
plot(g)                  

Variable color encoding

#COLOR BASED ON ANOTHER COLUMN
# Not just color, but size, shape, stroke (thickness of boundary)
# and fill (fill color) can be used to discriminate groupings.
g <- ggplot(midwest, aes(x=area, y=poptotal))+     #TELL IT WHAT TO PLOT
geom_point(aes(col=state), size=3) +               #DO SCATTER PLOT
#LEGEND ADDED AUTOMATICALLY
# theme(legend.position="None")+                   #REMOVE LEGEND
#se=FALSE  --> TURN OFF CONFIDENCE BANDS
geom_smooth(method="lm", col="firebrick", size=2)+ #ADD LINEAR BEST FIT LINE
coord_cartesian(xlim=c(0,0.1), ylim=c(0, 200000))+ #SET LIMITS
labs(title="Area Vs Population",                   #SET LABELS
subtitle="From midwest dataset",
y="Population (count)",
x="Area (square miles)",
caption="Midwest Demographics")+
scale_colour_brewer(palette = "Spectral")         #CHANGE COLOR PALETTE
plot(g)                                            #GENERATE PLOT

Part-3: Assignment (plot re-creation)

  • Insert code below to re-create the following plots EXACTLY
    • use palette = "Pastel1"
  • Do NOT use any built in themes
  • Make sure to comment your code carefully

Lab-1.1.1:

#AXIS FONT AND TICS
# Not just color, but size, shape, stroke (thickness of boundary)
# and fill (fill color) can be used to discriminate groupings.

# have used 2 methods for formatting
# labels: * Method 1: Using sprintf().
# (Have formatted it as % in below example) * Method 2: Using a custom user defined
# function. (Formatted 1000’s to 1K scale)
dx <- 0.02
FS <- 14
g <- ggplot(midwest, aes(x=area, y=poptotal))+     #TELL IT WHAT TO PLOT
geom_point(aes(col=state), size=3) +               #DO SCATTER PLOT

#LEGEND ADDED AUTOMATICALLY
# theme(legend.position="None")+                   #REMOVE LEGEND
#se=FALSE  --> TURN OFF CONFIDENCE BANDS
geom_smooth(method="lm", col="#5ea4bd", size=2)+ #ADD LINEAR BEST FIT LINE
coord_cartesian(xlim=c(0,0.1), ylim=c(0, 600000))+ #SET LIMITS
labs(title="Area Vs Population",                   #SET LABELS
subtitle="From midwest dataset",
y="Population (count)",
x="Area (square miles)",
caption="Midwest Demographics")+
scale_colour_brewer(palette = "Pastel1")+         #CHANGE COLOR PALETTE

# XTICS MARKS
scale_x_continuous(breaks=seq(0, 0.1, dx), labels = sprintf("%1.2f", seq(0, 0.1, dx))) +
scale_y_continuous(breaks=seq(0, 600000, 200000), labels = function(x){paste0(x/1000, 'K')})+

# FONT SIZE
theme(
axis.text.x = element_text(angle=90, hjust=1,size=FS),
axis.text.y = element_text(size=FS),
axis.title.x= element_text(size=FS),
axis.title.y= element_text(size=FS),
panel.background = element_rect(fill = 'white', color = 'black')
)
# RENDER PLOT
plot(g)