# Tell R we are using the ggplot2 plotting library. This is the equivalent of an import statement in Python. library(ggplot2) # Read the file into a dataframe guns <- read.csv("nics-firearm-background-checks.csv") # There are a lot of columns in the dataframe, so we will only keep the first 8 columns, # to make it easier to see what is happening in the dataframe. guns <- guns[,1:8] # Tell R that the month column contains dates, so that it can interpret them that way. # Unfortunately, the built-in data converter in R needs the day of the month, which our data doesn't have. # So we will add -01 to all the dates, so that the date is the 1st of each month. guns$month <- paste(guns$month,"-01",sep="") # Convert the month column into R dates guns$month <- as.Date(guns$month) # ggplot works by adding together the components that make up the plot: # set up the plot using the guns dataframe, with x being the month column data and y being the handgun column data ggplot(guns,aes(x = month, y = handgun)) + # add ploints to the plot that are red (if you don't put a color, the default is black) geom_point(color = "red") + # add a title to the plot ggtitle("# of handgun background checks") # The previous plot plotted all numbers for all states for all dates, so it was hard to understand what was happening. # Let's just look at New York. # Make a new dataframe with only the New York data. guns_NY <- subset(guns,subset = state == "New York") # Make the same plot as above, but using only the New York state data. ggplot(guns_NY,aes(x = month, y = handgun)) + geom_point(color = "red") + ggtitle("# of handgun background checks") # This is the same as the previous plot, but uses a line instead of points to show the data. ggplot(guns_NY,aes(x = month, y = handgun)) + geom_line(color = "red") + ggtitle("# of handgun background checks") # We will make a dataframe with only the data from 5 states. guns_5states <- subset(guns,subset = state == "New York" | state == "California" | state == "North Carolina" | state == "Alaska" | state == "Louisiana") # This is the same as the previous plot, but uses the 5 states dataframe instead of the one with only New York. # Also, we add the option color = factor(state) to tell R that all rows with the same state should have the same color. ggplot(guns_5states,aes(x = month, y = handgun,color = factor(state))) + geom_line() + ggtitle("# of handgun background checks") # This is the same as the previous plot, but we plot the long_gun column instead of the handgun column. ggplot(guns_5states,aes(x = month, y = long_gun,color = factor(state))) + geom_line() + ggtitle("# of handgun background checks")