Skip to content

Instantly share code, notes, and snippets.

@dfkoz
Created February 6, 2012 16:13
Show Gist options
  • Select an option

  • Save dfkoz/1752994 to your computer and use it in GitHub Desktop.

Select an option

Save dfkoz/1752994 to your computer and use it in GitHub Desktop.
R code used to create and save a time-lapse bar chart
# Set up the bar colors
bar_color <- c("dodgerblue4", "darkseagreen4", "firebrick4")
# Set up the column name vector
col_names <- c("Public", "Private", "Total")
# clean up old images
file.remove(list.files(pattern=".png"))
# Loop through each year in the dataset
for(i in 1:65) {
# make sure single-digit names have a leading 0
if (i < 10) {
name = paste("img0", i, ".png", sep="")
}
else {
name = paste("img", i, ".png", sep="")
}
# create the new PNG file, and set up the new plot
png(name)
plot.new()
par(pin=c(5.0, 4.0))
# Put this year's data into vect
vect <- c(ed_data$Students.per.Teacher...Public[i],
ed_data$Students.per.Teacher...Private[i],
ed_data$Students.per.Teacher...Total[i])
# Create the bar graph with this year's data,
# the colors we configured earlier,
# a fixed y limit, custom spacing,
# a label, and some bolded text
barplot(vect, col=bar_color,
names=col_names,
ylim=c(0, 35),
space = 0.7,
ylab="Students per Teacher",
font.lab=2,
font.axis=2
)
# Draw a box around the plot and a title above it
box()
title(main = list("US Student / Teacher Ratio",
col="cadetblue4", cex=2.0))
# Draw the black outline for the "time-lapse" box
rect(0.52, 33, 5.27, 35)
# Draw the filling for the time-lapse box
rect(0.52, 33, 0.52 + i / 65 * (5.27 - 0.52),
35,
col=rgb(0.1 + 0.1 * i / 65, 0.5 + 0.5 * i / 65, 0.1 + 0.1 * i / 65)
)
# Write the year into the time-lapse box, and flip it as
# the label gets too close to the right side of the graph
if (i < 50) {
text(0.52 + i / 65 * (5.27 - 0.52) + 0.3, 34.25,
labels=c(ed_data$Year[i]))
} else {
text(0.52 + i / 65 * (5.27 - 0.52) - 0.3, 34.25, labels=c(ed_data$Year[i]))
}
dev.off()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment