Skip to content

Instantly share code, notes, and snippets.

@paynito
Created September 1, 2016 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paynito/878bc5e151ca134f823013194ebe5020 to your computer and use it in GitHub Desktop.
Save paynito/878bc5e151ca134f823013194ebe5020 to your computer and use it in GitHub Desktop.
---
title: "2 groups of 3 box-plots"
author: "Benyomin Hagalili"
date: "8/31/2016"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Adapted from:
https://www.r-bloggers.com/side-by-side-box-plots-with-patterns-from-data-sets-stacked-by-reshape2-and-melt-in-r/
Create a boxplot to illustrate the range of Incomes
as it varies by city
```{r create data}
# duplicate 1 # to make a mode
nyc_income1984 <- c(4,246,24,34,234,553,34)
dfw_income1984 <- c(344, 423,522, 234, 522, 255)
okc_income1984 <-c(234,234,236,99,184,301)
# pad any short columns with NA
max.len = max(length(nyc_income1984),length(dfw_income1984),length(okc_income1984))
nyc1984 <-c(nyc_income1984, rep(NA, max.len-length(nyc_income1984)))
dfw1984 <-c(dfw_income1984, rep(NA, max.len-length(dfw_income1984)))
okc1984 <-c(okc_income1984,rep(NA, max.len-length(okc_income1984)))
nyc1985 <- nyc1984*1.4
dfw1985 <- dfw1984+50
okc1985 <- okc1984*.7
location <- c('NYC','DFW','OKC','NYC','DFW','OKC')
year<- c(1984,1984,1984,1985,1985,1985)
library(reshape2)
#combine the data
all.data = data.frame(rbind
(nyc1984,dfw1984,okc1984,
nyc1985,dfw1985,okc1985)
)
#head(all.data)
# add locations and years to the data
all.data$location #nothing there yet
all.data$location <- location
all.data$year <- year
head(all.data)
# stack the data
stacked.data = melt(all.data,id =c('location','year'))
head(stacked.data)
# remove the column w/ variable name
incomeByCity <- stacked.data[,-3]
```
Now the data is in a form ready for the boxplot package.
```{r plotMyCities}
#colors from https://www.r-bloggers.com/box-plot-with-r-tutorial/
#error on paste
# convert curly-smart quotes to normal with
# http://dan.hersam.com/tools/smart-quotes.html
boxplots.triple = boxplot(value~location+year,
data = incomeByCity,
ylab = "Individual Income in $/month",
las = 2,
at = c(1,1.8,2.6,6,6.8,7.6),
names = location,
xaxt = 'n',
ylim=c(0,800),
col = c("sienna","palevioletred1","royalblue2","sienna","palevioletred1","royalblue2")
)
boxplots.triple
text(c(1,1.8,2.6,6,6.8,7.6),c(6,8,1,17.5,20,15.5),location)
axis(side=1, at=c(1.8,6.8), labels=c(1984,1985))
title('Individual Income in 3 cities, 1984 and 1985')
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment