This lesson is being piloted (Beta version)

Ploting with ggplot

Overview

Teaching: 30 min
Exercises: 0 min
Questions
  • How to plot in R using ggplot2 package

Objectives
  • Learn professional plotting tool in R using ggplot2

  • Learn multiple way to use ggplot2

What is ggplot

Basic component of ggplot

Type of ggplot

Basic qplot: Scatter plot

Basic qplot: Histogram

qplot(Sepal.Length,fill=Species, data=iris)
qplot(Sepal.Length,data=iris,geom="density")
qplot(Sepal.Length,data=iris,geom="density",
      color=Species)

image

Basic qplot: Facets

qplot(Sepal.Length,Petal.Length,facets=.~Species, data=iris)

image

Advanced ggplot

Sample plot

gp <- ggplot(mpg, aes(hwy, cty))

gp+geom_point(aes(color=cyl))
gp+geom_point(aes(color=factor(cyl)))
gp+geom_point(aes(color=factor(cyl)))+geom_smooth(method="lm")
gp+geom_point(aes(color=factor(cyl)))+geom_smooth(method="lm")
  +facet_grid(.~cyl)
# Save plot to file
ggsave("plot.png",width=5,height=5)

image

Annotation

Some nice ggplots featuring

Boxplot

ggplot(mpg,aes(x=manufacturer,y=hwy,
               fill=factor(manufacturer)))+
  geom_boxplot()+
  geom_jitter()+
  labs(title="Boxplot for Hwy per manufacturer",x="Manufacturer",y="Highway milage")+
  theme_bw()+coord_flip()+
  theme(legend.position = "none")

image

Violin plot

g <- ggplot(mpg, aes(class, cty))
g + geom_violin(aes(fill=class)) + 
  labs(title="Violin plot", 
       subtitle="City Mileage vs Class of vehicle",
       caption="Source: mpg",
       x="Class of Vehicle",
       y="City Mileage")

image

Histogram

g <- ggplot(mpg, aes(displ)) + scale_fill_brewer(palette = "Spectral")
g + geom_histogram(aes(fill=class), 
                   bins=10, 
                   col="black", 
                   size=.1) +   # change number of bins
  labs(title="Histogram with Fixed Bins", 
       subtitle="Engine Displacement across Vehicle Classes",
       x="enginer displacement (m)",
       y="Frequency count") 

image

Scatter plot

data("midwest")
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(subtitle="Area Vs Population", 
       y="Population", 
       x="Area", 
       title="Scatterplot", 
       caption = "Source: midwest")
plot(gg)

image

Density

g <- ggplot(mpg, aes(cty))
g + geom_density(aes(fill=factor(cyl)), alpha=0.8) + 
    labs(title="Density plot", 
         subtitle="City Mileage Grouped by Number of cylinders",
         caption="Source: mpg",
         x="City Mileage",
         fill="# Cylinders")+
    theme_bw()

image

Density 2D

gg <- ggplot(faithful,aes(x=eruptions,y=waiting))
gg + stat_density_2d(aes(fill=..level..),
                     geom="polygon",color="black")+
     geom_smooth(method="lm",linetype=2,color="red")+
     scale_fill_continuous(low="green",high="red")+
     geom_point() +
     theme_bw()

image

Geographic visualization with ggplot

library(maps)
states <- map_data("state")
ggplot(data = states)+
  geom_polygon(aes(x=long,y=lat,fill=region),
               color="black")+
  coord_fixed(1.3)+
  guides(fill=FALSE)

image

counties <- map_data("county")
SC_counties <- subset(counties,region == "south carolina")
ggplot(data = SC_counties)+
  geom_polygon(aes(x=long,y=lat,fill=subregion),
               color="black")+
  coord_fixed(1.3)+
  guides(fill=FALSE)

image

some.eu.countries <- c(
  "Portugal", "Spain", "France", "Switzerland", "Germany",
  "Austria", "Belgium", "UK", "Netherlands",
  "Denmark", "Poland", "Italy", 
  "Croatia", "Slovenia", "Hungary", "Slovakia",
  "Czech republic"
)
# Retrievethe map data
some.eu.maps <- map_data("world", region = some.eu.countries)

ggplot(some.eu.maps, aes(x = long, y = lat)) +
  geom_polygon(aes( group = group, fill = region))+
  scale_fill_viridis_d()+
  theme_void()+
  theme(legend.position = "none")

image

Plot Shapefile for geography study

Download shape file data [here](https://opendata.arcgis.com/datasets/a21fdb46d23e4ef896f31475217cbb08_1.zip)
Store it in your folder: c:/R/GIS/ in Windows or /user/R/GIS in MacOS
Unzip it and rename all files to `Countries_WGS84.*` under `C:/GIS/`

Install additional packages:

install.packages("rgdal")
install.packages("colorspace")

Perform plotting

library(rgdal)
library(colorspace)
library(maps)

setwd('c:/R/GIS/')
gfile <- readOGR(dsn="Countries_WGS84.shp")
names(gfile)
gfile$CNTRY_NAME

plot(gfile)
plot(gfile,col=rainbow_hcl(50))
llgridlines(gfile,lty=5)

image

Plot raster

Here we will plot a raster data base using Global land cover data set. The data can be downloaded from here. Unzip and put the raster data to working directory:

install.packages("raster")
library(raster)
library(rgdal)

setwd('c:/R/GIS/')
#import raster
Gcover <- raster("GLOBCOVER_L4_200901_200912_V2.3.tif")
#plot raster
plot(Gcover,main="GLobal Land cover")

image

Key Points

  • ggplot2