Repository navigation
Assignment 2
library(ggplot2) # need this to use'ggplot' library(ggthemes) # many additional beautiful themes library(gridExtra) # replaces 'par()' We still need to do the data work..
df = read.csv("~/Desktop/p3/outcome-of-care-measures.csv", colClasses = "character")
colnames(df)[11] = "HeartAttack" colnames(df)[17] = "HeartFailure" colnames(df)[23] = "Pneumonia"
df$HeartAttack = as.numeric(df$HeartAttack) df$HeartFailure = as.numeric(df$HeartFailure) df$Pneumonia = as.numeric(df$Pneumonia)
rHA = range(df$HeartAttack, na.rm = TRUE) rHF = range(df$HeartFailure, na.rm = TRUE) rP = range(df$Pneumonia, na.rm = TRUE)
rng = c(min(c(rHA[1], rHF[1], rP[1])), max(c(rHA[2], rHF[2], rP[2])))
meanHeartAttack = round(mean(df$HeartAttack, na.rm = TRUE)) meanHeartFailure = round(mean(df$HeartFailure, na.rm = TRUE)) meanPneumonia = round(mean(df$Pneumonia, na.rm = TRUE)) Here's where the ggplot work comes in. We build three graphs of the death rate for each condition and put them into a grid.
I like to put each ggplot element on a separate line as I'm building a plot, and that also makes it easier to explain what's going on:
You can see that we start by calling ggplot() and tell it which data frame (df) we're working with. We then tell it we're using the heart attack death rate data and that we want to plot a histogram (using density vs frequency). We then layer the smooth density estimate line over the histogram. And, then plot the median value. We set the labels. And, modify the scale (as instructed). I added the theme_few() to make it prettier than the ggplot defaults (try it without that line) Lather/rinse/repeat for each death reate.
haPlot = ggplot(df, aes(x = HeartAttack)) + geom_histogram(aes(y = ..density..), fill = "lightblue", color = "black") + geom_density() + geom_vline(xintercept = median(df$HeartAttack, na.rm = TRUE), color = "maroon") + labs(title = paste("Heart Attack 30-day Death Rate ( X =", meanHeartAttack, ")"), x = "30-day Death Rate") + scale_x_continuous(limits = rng) + theme_few()
hfPlot = ggplot(df, aes(x = HeartFailure)) + geom_histogram(aes(y = ..density..), fill = "lightblue", color = "black") + geom_density() + geom_vline(xintercept = median(df$HeartFailure, na.rm = TRUE), color = "maroon") + labs(title = paste("Heart Failure 30-day Death Rate ( X =", meanHeartFailure, ")"), x = "30-day Death Rate") + scale_x_continuous(limits = rng) + theme_few()
pnPlot = ggplot(df, aes(x = Pneumonia)) + geom_histogram(aes(y = ..density..), fill = "lightblue", color = "black") + geom_density() + geom_vline(xintercept = median(df$Pneumonia, na.rm = TRUE), color = "maroon") + labs(title = paste("Pneumonia 30-day Death Rate ( bar(X) =", meanPneumonia, ")"), x = "30-day Death Rate") + scale_x_continuous(limits = rng) + theme_few()