In this exercise you will learn to plot data using the ggplot2 package. To answer the questions below, use Chapter 4.3 Categorical vs. Quantitative Data Visualization with R.

# Load packages
library(tidyquant)
library(tidyverse)

# Import stock prices
stock_prices <- tq_get(c("AAPL", "MSFT"), get  = "stock.prices", from = "2020-01-01")

Q1 Select Apple stock prices and save it under plotdata.

Hint: See the code in 4.2.2 Line plot.

# Select US cases
library(dplyr)
plotdata <- filter(stock_prices, 
                   symbol == "AAPL")

Q2 Create a simple line plot with date on the x-axis and closing price on the y-axis.

Hint: See the code in 4.2.2 Line plot.

# simple line plot
ggplot(plotdata, 
       aes(x = date, 
           y = close)) +
  geom_line() 

Q3 Add the color (cornflowerblue) to the line plot.

Hint: See the code in 4.2.2 Line plot.

ggplot(plotdata, 
       aes(x = date, 
           y = close)) +
  geom_line(color = "cornflowerblue")

Q4 Make the line thicker in the line plot.

Hint: See the code in 4.2.2 Line plot.

ggplot(plotdata, 
       aes(x = date, 
           y = close)) +
  geom_line(line = 3)
## Warning: Ignoring unknown parameters: line

Q5 Label the y-axis as “Closing Price”.

Hint: See the code in 4.2.2 Line plot.

ggplot(plotdata, 
       aes(x = date, 
           y = close)) +
geom_line() +
  labs(y = "Closing Price")  

Q6 Remove the label of the x-axis.

Hint: See the code in 4.2.2 Line plot.

ggplot(plotdata, 
       aes(x = date, 
           y = close)) +
geom_line() +
  labs(x = "")  

Q7 Create the line plot for both Apple and Microsoft.

Hint: Google search something like “ggplot2 two lines”.

plotdata2 <- filter(stock_prices, 
                   symbol == "MSFT") 
      

ggplot() + 
  geom_line(data = plotdata, aes(x = date, y = close), color = "darkred") + 
  geom_line(data = plotdata2, aes(x = date,y = close), color="steelblue") 

Q8 Hide the messages, but display the code and its results on the webpage.

Hint: Use message, echo and results in the chunk options. Refer to the RMarkdown Reference Guide.

knitr::opts_chunk$set(echo = TRUE, message = FALSE, results = "markup")

Q9 Display the title and your name correctly at the top of the webpage.

Q10 Use the correct slug.