To produce the plot, we began by constructing a data frame with 28 rows and 3 columns. The data indicate respondents' attitude shifts across a variety of political categories from 2010 to 2012. The rows in the data frame are divided into the following 7 categories:
The columns in the data frame indicate the politcal categories assessed, respondents' approval ratings of each category, and the two years in which the data are being compared (2010 & 2012).
The data were retrieved from the following URL: http://surveys.ap.org/data/GfK/AP_Racial_Attitudes_Topline_09182012.pdf
The desired information from the the political categories of the orginal study have been rearranged in Microsoft Excel as reflected by the table below. The data were then saved as a “comma separated value” file named “Politics2012.csv”.
Political Category | Rating | Year |
---|---|---|
Obama Performance | 19 | 1 |
Obama Performance | 13 | 2 |
Obama Performance | 29 | 1 |
Obama Performance | 29 | 2 |
Economy | 11 | 1 |
Economy | 8 | 2 |
Economy | 25 | 1 |
Economy | 19 | 2 |
Terrorism | 11 | 1 |
Terrorism | 16 | 2 |
Terrorism | 26 | 1 |
Terrorism | 26 | 2 |
Unemployment | 10 | 1 |
Unemployment | 7 | 2 |
Unemployment | 22 | 1 |
Unemployment | 20 | 2 |
Environment | 12 | 1 |
Environment | 10 | 2 |
Environment | 23 | 1 |
Environment | 23 | 2 |
Energy | 12 | 1 |
Energy | 10 | 2 |
Energy | 24 | 1 |
Energy | 23 | 2 |
Gas Prices | 7 | 1 |
Gas Prices | 4 | 2 |
Gas Prices | 18 | 1 |
Gas Prices | 12 | 2 |
R allows its users to “read in” data and assign it to a vector which allows the user to recall, interpret, and/or analyze the data in a variety of ways.
The following r script demonstrates how to assign the tabled data above to a vector called “Politics2012”.
Politics2012 <- read.csv("C:/Users/iman/Desktop/Politics2012.csv")
In order to plot or graph imported data using r, users are required to download one of a variety of external “packages” (each of which provides r with the capability to present data in unique and useful ways). To graph the information in the table shown above, the “ggplot2” package was installed into r from the ggplot2 library. (Needed packages must be installed into r each time the program is opened). To create the plot Using RStudio, click on the “packages” icon in the lower right quadrant of the screen, scroll down to “ggplot2”, and check the box. If loading ggplot2 manually, follow the r-script provided below.
Use the following script file to produce the box-and-whiskers plot:
# To load ggplot2 library, enter the following r script code:
library(ggplot2)
# Divide the 'year' column it into 2010 and 2012 with:
Politics2012$year = factor(Politics2012$year, labels = c("2010", "2012"))
ggplot(data = Politics2012, aes(x = Category, y = Rating, fill = factor(year))) +
geom_boxplot() + scale_fill_brewer(palette = "Set1") + ylab("Respondent's Ratings") +
xlab("Political Categories") + theme_bw()