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")
stock_prices
## # A tibble: 66 x 8
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2020-01-02 296. 301. 295. 300. 33870100 300.
## 2 AAPL 2020-01-03 297. 301. 296. 297. 36580700 297.
## 3 AAPL 2020-01-06 294. 300. 293. 300. 29596800 299.
## 4 AAPL 2020-01-07 300. 301. 297. 298. 27218000 298.
## 5 AAPL 2020-01-08 297. 304. 297. 303. 33019800 302.
## 6 AAPL 2020-01-09 307. 310. 306. 310. 42527100 309.
## 7 AAPL 2020-01-10 311. 313. 308. 310. 35161200 310.
## 8 AAPL 2020-01-13 312. 317. 311. 317. 30383000 316.
## 9 AAPL 2020-01-14 317. 318. 312. 313. 40488600 312.
## 10 AAPL 2020-01-15 312. 316. 310. 311. 30480900 311.
## # … with 56 more rows
Hint: See the code in 4.2.2 Line plot.
library(dplyr)
plotdata <- filter(stock_prices,
symbol == "AAPL")
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(size = 1.5, color = "cornflowerblue")
Hint: See the code in 4.2.2 Line plot.
ggplot(plotdata,
aes(x = date,
y = close)) +
geom_line(size = 1.5, color = "cornflowerblue") +
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(size = 1.5, color = "cornflowerblue") +
labs(y = "Closing Price",
x = "")
## Q7 Create the line plot for both Apple and Microsoft. Hint: Google search something like “ggplot2 two lines”.
ggplot(stock_prices,
aes(x = date,
y = close,
col = symbol)) +
geom_line()
Hint: Use message, echo and results in the chunk options. Refer to the RMarkdown Reference Guide.