Part 2 ggplot2 - Replication of few graphs/charts in base R, ggplot2, and rCharts

In this series of 3 posts, I use a simulated dataset (7 variables -3 factor and 4 numeric - and a sample size of 50) to create graphs/charts using base R, and replicate them using ggplot2, and rCharts. This is not an attempt to create an exhaustive database of graphs/charts of all possible combinations, but it was an exercise to generate some of the common ones (in my view). These include dot plots, histograms, box plots, bar charts, scatter plots, density curves, and line graphs and a few more. I am sure the code can be further optimized and it could use some finishing touches with many things like legends, axes labels, and color, but at the core, I think it does its job. Thanks to Ramnath Vaidyanathan for having answers to all questions and to the kind rCharts, ggplot2, and R community for the free knowledge base available on the Internet. The code for these pages can be found on github.

Part 1 in the series (using Base R) can be found here

Part 3 in the series (using rCharts) can be found here


Let us begin by simulating our sample data of 3 factor variables and 4 numeric variables.

## Simulate some data

## 3 Factor Variables

## 4 Numeric Vars
NumVar1=round(rnorm(n=50,mean=1000,sd=50),digits=2) ## Normal distribution
NumVar2=round(runif(n=50,min=500,max=1500),digits=2) ## Uniform distribution
NumVar3=round(rexp(n=50,rate=.001)) ## Exponential distribution


Initialize the libraries used for this page


One Variable: Numeric Variable

ggplot(simData,aes(y=NumVar1,x=1:nrow(simData),group="NumVar1"))+geom_point()+geom_line()+ xlab("") ## Index plot 

plot of chunk unnamed-chunk-3

ggplot(simData,aes(x=NumVar1))+geom_histogram() ## histogram

plot of chunk unnamed-chunk-3

ggplot(simData,aes(x=NumVar1))+geom_density() ## Kernel density plot

plot of chunk unnamed-chunk-3

ggplot(simData,aes(x=factor(""),y=NumVar1))+geom_boxplot()+ xlab("") ## box plot

plot of chunk unnamed-chunk-3

One Variable: Factor Variable

## barplot

plot of chunk unnamed-chunk-4

## pie chart - Not the best graph --- use with caution
ggplot(simData,aes(x = factor(""), fill=FacVar3, label=FacVar3))+geom_bar()+ coord_polar(theta = "y")  +scale_x_discrete("")

plot of chunk unnamed-chunk-4

Two Variables: Two Numeric Variables

simtmp=simData[,c(4:5)] ## 4th and 5th columns are NumVar1 and NumVar2

## line plots with observation number as index

plot of chunk unnamed-chunk-5

## Let's draw density functions for NumVar1 & NumVar2

plot of chunk unnamed-chunk-5

## scatter plot

plot of chunk unnamed-chunk-5

Two Variables: Two Factor Variables

## Mosaic plot: ggMMplot function - thanks to Edwin on Stackoverflow:

ggMMplot <- function(var1, var2){
  levVar1 <- length(levels(var1))
  levVar2 <- length(levels(var2))
  jointTable <- prop.table(table(var1, var2))
  plotData <-
  plotData$marginVar1 <- prop.table(table(var1))
  plotData$var2Height <- plotData$Freq / plotData$marginVar1
  plotData$var1Center <- c(0, cumsum(plotData$marginVar1)[1:levVar1 -1]) +
    plotData$marginVar1 / 2
  ggplot(plotData, aes(var1Center, var2Height)) +
    geom_bar(stat = "identity", aes(width = marginVar1, fill = var2), col = "Black") +
    geom_text(aes(label = as.character(var1), x = var1Center, y = 1.05)) 
ggMMplot(simData$FacVar2, simData$FacVar3)

plot of chunk unnamed-chunk-6

## barplots

bartabledat =$FacVar2, simData$FacVar3)) ## get the cross tab
ggplot(bartabledat,aes(x=Var2,y=Freq,fill=Var1))+geom_bar(position="dodge") ## plot

plot of chunk unnamed-chunk-6

ggplot(bartabledat,aes(x=Var2,y=Freq,fill=Var1))+geom_bar() ## stacked

plot of chunk unnamed-chunk-6

bartableprop$FacVar2, simData$FacVar3),2)*100) 
ggplot(bartableprop,aes(x=Var2,y=Freq,fill=Var1))+geom_bar() ## Stacked 100% 

plot of chunk unnamed-chunk-6

Two Variables: One Factor and One Numeric

## Box plots for the numeric var over the levels of the factor var

plot of chunk unnamed-chunk-7

## density plot of numeric var across multiple levels of the factor var

plot of chunk unnamed-chunk-7

## Mean of one numeric var over levels of one factor var
meanagg = aggregate(simData$NumVar1, list(simData$FacVar3), mean)
ggplot(meanagg,aes(x=Group.1,y=x))+geom_point()+coord_flip() ## Dot Chart equivalent

plot of chunk unnamed-chunk-7

ggplot(meanagg,aes(x=Group.1,y=x))+geom_bar() ## Bar plot

plot of chunk unnamed-chunk-7

Three Variables: Three Factor Variables

Threebartable =$FacVar1, simData$FacVar2, simData$FacVar3)) ## CrossTab
ggplot(Threebartable,aes(x=Var3,y=Freq,fill=Var2))+geom_bar(position="dodge")+facet_wrap(~Var1) ## Bar plot with facetting

plot of chunk unnamed-chunk-8

Three Variables: One Numeric and Two Factor Variables

## boxplot of NumVar1 over an interaction of 6 levels of the combination of FacVar1 and FacVar2
ggplot(simData,aes(x=FacVar2,y=NumVar1, fill=FacVar1))+geom_boxplot()

plot of chunk unnamed-chunk-9

## Mean of 1 Numeric over levels of two factor vars
meanaggg = aggregate(simData$NumVar1, list(simData$FacVar1, simData$FacVar2), mean)
## Dot Chart equivalent
ggplot(meanaggg,aes(x=Group.2,y=x,color=Group.2))+geom_point()+coord_flip()+facet_wrap(~Group.1, ncol=1) 

plot of chunk unnamed-chunk-9

## Interaction chart - line chart
ggplot(meanaggg,aes(x=Group.2,y=x,color=Group.1, group=Group.1))+geom_point()+geom_line()

plot of chunk unnamed-chunk-9

## And bar plot

plot of chunk unnamed-chunk-9

Three Variables: Two Numeric and One Factor Variables

## Scatter plot with color identifying the factor variable

plot of chunk unnamed-chunk-10

Three Variables: Three Numeric Variables

## NumVar4 is 2001 through 2050... possibly, a time variable - use that as the x-axis

plot of chunk unnamed-chunk-11

## Extra: Stacked Area Graph

plot of chunk unnamed-chunk-11

## Extra: 100% stacked area graph

plot of chunk unnamed-chunk-11

## ## Bubble plot - scatter plot of NumVar1 and NumVar2 with individual observations sized by NumVar3

plot of chunk unnamed-chunk-11

Scatterplot Matrix of all Numeric Vars, colored by a Factor variable

#Thanks to Gaston Sanchez for the function:
 makePairs <- function(data) 
  grid <- expand.grid(x = 1:ncol(data), y = 1:ncol(data))
  grid <- subset(grid, x != y)
  all <-"rbind", lapply(1:nrow(grid), function(i) {
    xcol <- grid[i, "x"]
    ycol <- grid[i, "y"]
    data.frame(xvar = names(data)[ycol], yvar = names(data)[xcol], 
               x = data[, xcol], y = data[, ycol], data)
  all$xvar <- factor(all$xvar, levels = names(data))
  all$yvar <- factor(all$yvar, levels = names(data))
  densities <-"rbind", lapply(1:ncol(data), function(i) {
    data.frame(xvar = names(data)[i], yvar = names(data)[i], x = data[, i])
  list(all=all, densities=densities)

## expanding numeric columns for pairs plot
gg1 = makePairs(simData[,4:7])

## new data frame 
simDatabig = data.frame(gg1$all,simData[,1:3])

## pairs plot
ggplot(simDatabig, aes_string(x = "x", y = "y")) + 
  facet_grid(xvar ~ yvar, scales = "free") + 
  geom_point(aes(colour=FacVar2), na.rm = TRUE) + 
  stat_density(aes(x = x, y = ..scaled.. * diff(range(x)) + min(x)), 
               data = gg1$densities, position = "identity", 
               colour = "grey20", geom = "line")

plot of chunk unnamed-chunk-12


Besides the link to Edwin’s response from Stackoverflow and Gaston Sanchez’s site referred to above, other resources used and useful for ggplot2 include the following.