In this exercise, you will learn to create line plot using the ggplot2 package. To answer the questions below, use Chapter 4.2 Quantitative 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")
stock_prices
## # A tibble: 582 x 8
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2020-01-02 74.1 75.2 73.8 75.1 135480400 74.3
## 2 AAPL 2020-01-03 74.3 75.1 74.1 74.4 146322800 73.6
## 3 AAPL 2020-01-06 73.4 75.0 73.2 74.9 118387200 74.2
## 4 AAPL 2020-01-07 75.0 75.2 74.4 74.6 108872000 73.8
## 5 AAPL 2020-01-08 74.3 76.1 74.3 75.8 132079200 75.0
## 6 AAPL 2020-01-09 76.8 77.6 76.6 77.4 170108400 76.6
## 7 AAPL 2020-01-10 77.7 78.2 77.1 77.6 140644800 76.8
## 8 AAPL 2020-01-13 77.9 79.3 77.8 79.2 121532000 78.4
## 9 AAPL 2020-01-14 79.2 79.4 78.0 78.2 161954400 77.4
## 10 AAPL 2020-01-15 78.0 78.9 77.4 77.8 121923600 77.1
## # … with 572 more rows
Hint: See the code in 4.2.2 Line plot.
plotdata <- filter(stock_prices, symbol == "AAPL")
plotdata
## # A tibble: 291 x 8
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2020-01-02 74.1 75.2 73.8 75.1 135480400 74.3
## 2 AAPL 2020-01-03 74.3 75.1 74.1 74.4 146322800 73.6
## 3 AAPL 2020-01-06 73.4 75.0 73.2 74.9 118387200 74.2
## 4 AAPL 2020-01-07 75.0 75.2 74.4 74.6 108872000 73.8
## 5 AAPL 2020-01-08 74.3 76.1 74.3 75.8 132079200 75.0
## 6 AAPL 2020-01-09 76.8 77.6 76.6 77.4 170108400 76.6
## 7 AAPL 2020-01-10 77.7 78.2 77.1 77.6 140644800 76.8
## 8 AAPL 2020-01-13 77.9 79.3 77.8 79.2 121532000 78.4
## 9 AAPL 2020-01-14 79.2 79.4 78.0 78.2 161954400 77.4
## 10 AAPL 2020-01-15 78.0 78.9 77.4 77.8 121923600 77.1
## # … with 281 more rows
Hint: See the code in 4.2.2 Line plot.
ggplot(plotdata,
aes(x = date,
y = close)) +
geom_line()
Hint: See the code in 4.2.2 Line plot.
ggplot(plotdata,
aes(x = date,
y = close)) +
geom_line(color = "cornflowerblue")
Hint: See the code in 4.2.2 Line plot.
ggplot(plotdata,
aes(x = date,
y = close)) +
geom_line(color = "cornflowerblue", size = 2)
Hint: See the code in 4.2.2 Line plot.
ggplot(plotdata,
aes(x = date,
y = close)) +
geom_line(color = "cornflowerblue", size = 2) +
labs(y = "Closing Price")
Hint: See the code in 4.2.2 Line plot.
ggplot(plotdata,
aes(x = date,
y = close)) +
geom_line(color = "cornflowerblue", size = 2) +
labs(y = "Closing Price", x = "")
Hint: Google search something like “ggplot2 two lines”.
ggplot(stock_prices,
aes(x = date,
y = close, color = symbol)) +
geom_line(size = 2) +
labs(y = "Closing Price", x = "")
Hint: Use message, echo and results in the chunk options. Refer to the RMarkdown Reference Guide.