Creating a plot

Our aim: Create a plot comparing the opinions of Amercian voters about Barak Obama and Donald Trump in 2016 (the year when Trump was elected). We have data from a pre-election survey with 1.200 respondents (American voters), called “American National Election Study” (ANES). Voters were asked questions about political opinions, the candidates, and so on. You can download the data set from the Canvas page if you want to reproduce the plot.

First step: Loading the ANES_pilot_2016 (a csv file) data set into RStudio. Store it the same folder where you run R. You find this folder on your computer with the function getwd().

getwd()
## [1] "C:/Users/Peter Maurer/Documents/R"

Next, must install (the first time you use it) and load (every time you use it) a R-package to load and visualize the data. We use the “tidyverse” package.

#install.packages("tidyverse")

library(tidyverse)

# now it's installed and loaded. With this package, you can load data in different formats and plot it (= create plots)

# We also use a package named "patchwork" to arrange the plots to one image.

#install.packages("patchwork")
library(patchwork)

Now, you must load the data set into R to work with it. There is a function to load .csv files called read_csv(). We give the data set which is now an object in R, a name, “anes”.

#this function reads the .csv data and stores it as a new object under the name "anes" 

anes <- read_csv("C:/Users/Peter Maurer/Documents/R/anes_pilot_2016.csv")

Next, we produce a plot for Obama and one for Trump. Opinions are measured on a thermometer with a scale from 0 = “very low opinion” to 100 = “very high opinion”. The name of the opinion variables is “fttrump” and “ftobama”. We need to use these variables for the plots.

#Creating two plots. The code is identical except for the variable with the opinion ft..

plot_obama<- ggplot(anes)+
  geom_histogram(aes(x = ftobama), binwidth = 1)+
  xlim(0,100)+
  labs(title ="Do you like Obama?")

plot_trump<- ggplot(anes)+
  geom_histogram(aes(x = fttrump), binwidth = 1)+
  xlim(0,100)+
  labs(title ="Do you like Trump?")


# Combining the plots using their object names

combined_plot <- plot_obama / plot_trump
combined_plot

Ready - you can now download and store the data and copy/paste the code to your Rstudio if you want try it out!