Basic Line Graph Coding in R

Using public information available from the Toronto Police, I analyzed vehicle collisions in Toronto from 1998-2012. I created a basic line graph in R to visualize the data.

I graphed the Percent of Fatal Collisions because I believe that fatal collisions are a stronger indicator of danger than total number of collisions. Collisions are unavoidable.  But if drivers follow the law and, more importantly, our car engineers develop safer cars, there should be no fatalities. Looking at the above graph shows a decrease in both number of collisions and the percent of fatal collisions. The fall in fatal collisions could be because of greater strides in safety engineering, greater penalties for reckless driving and more public awareness for better drivers. 
Here is my coding: 

#Vehicle Collisions in Toronto
#By Matthew Mano (matthewm3109@gmail.com)
collisions=read.csv(“TorontoCollisions.csv”, header=T) #upload csv file year=collisions$Year #Identify specific columns
total=collisions$C
fatal=collisions$Fpercent=(fatal/total)*100 #Find percent of Fatal Collisions to Total Number of Collisions
plot(year,total, type=“l”, xlab=“Year”, ylab=“Number of Collisions”) #Use type=”l” to create a line plot
par(new=TRUE) #keep working on the original graph
plot(year,percent,type=“l”,xaxt=“n”,yaxt=“n”,xlab=“”,ylab=“”,col=“red”)mtext(“Percent that were Fatal Collisions (%)”,side=4,line=3)axis(4) #Use right hand axix to display percent
legend(“topright”,col=c(“black”,“red”),lty=1,legend=c(“Number of Collisions”,“Percent that were Fatal Collisions”)) #Add legend title(main=“Vehicle Collisions in Toronto”) #Add title

The trickiest part was to generate a graph with two y-axis. I plotted the percent normally, then I added two special lines of code: 

mtext(“Percent that were Fatal Collisions (%)”,side=4,line=3)

Added the axis name to the margins. 

axis(4) #Use right hand axis to display percent 

Used the 4th ‘side’ of the graph – and the desired axis – to display gridlines 
I added link to download my full coding. Please let me know if I can improve this or add anything else. Let me know if you have any questions. 
Link to download code & download CSV and Excel file: http://bit.ly/1oBVFnj

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s