#install.packages(c(“ggplot2”, “scales”, “dplyr”))
#xét tập dữ liệu trong Kinh tế, có tên là Economies, đây là tập dữ liệu thu thập theo tháng tại Mỹ từ tháng 1 năm 1967 tới tháng 1 năm 2015. Mô phỏng biến psavert (personal savings rate - tỷ lệ tiết kiệm của cá nhân).
library(ggplot2)
library(scales)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
data("economics")
economics %>% head()
## # A tibble: 6 × 6
## date pce pop psavert uempmed unemploy
## <date> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1967-07-01 507. 198712 12.6 4.5 2944
## 2 1967-08-01 510. 198911 12.6 4.7 2945
## 3 1967-09-01 516. 199113 11.9 4.6 2958
## 4 1967-10-01 512. 199311 12.9 4.9 3143
## 5 1967-11-01 517. 199498 12.8 4.7 3066
## 6 1967-12-01 525. 199657 11.8 4.8 3018
ggplot(data = economics, mapping = aes(x = date, y = psavert)) +
geom_line() +
labs(title = "Tỉ lệ tiết kiệm các nhân",
x = "Thời Gian",
y = "Personal Savings Rate")
head(economics, n=4)#Tên bảng datafame, số dòng muốn xem
## # A tibble: 4 × 6
## date pce pop psavert uempmed unemploy
## <date> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1967-07-01 507. 198712 12.6 4.5 2944
## 2 1967-08-01 510. 198911 12.6 4.7 2945
## 3 1967-09-01 516. 199113 11.9 4.6 2958
## 4 1967-10-01 512. 199311 12.9 4.9 3143
# For more attractive graphs
# https://www.r-bloggers.com/2013/08/date-formats-in-r/
# Nạp các thư viện cần thiết
library(ggplot2)
library(plotly) # Chứa hàm ggplotly
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
library(scales) # Chứa hàm date_format
# Vẽ biểu đồ và gán vào p
p <- ggplot(data = economics, mapping = aes(x = date, y = psavert)) +
geom_line(color = "blue", size = 1) +
geom_smooth() +
# Sửa định dạng ngày tháng
scale_x_date(date_breaks = "4 years", labels = date_format("%b-%y")) +
labs(title = "Personal Savings Rate",
subtitle = "From 1967 to 2015",
x = "",
y = "Personal Savings Rate") +
theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
# Chuyển đổi sang biểu đồ tương tác
ggplotly(p)
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
#So sánh dữ liệu chứng khoán
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
##
## first, last
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(dplyr)
library(ggplot2)
library(scales)
# --- 1. Lấy dữ liệu Apple ---
# Dùng auto.assign = FALSE để gán trực tiếp dữ liệu vào biến 'apple'
apple <- getSymbols("AAPL", src = "yahoo",
return.class = "data.frame",
from = "2021-05-05",
auto.assign = FALSE)
# Xử lý dữ liệu Apple
apple <- apple %>%
mutate(Date = as.Date(row.names(.))) %>% # Chuyển row.names thành cột Date
select(Date, AAPL.Close) %>% # Chỉ lấy cột Date và giá đóng cửa
rename(Close = AAPL.Close) %>% # Đổi tên cột giá thành 'Close'
mutate(Company = "Apple")
# --- 2. Lấy dữ liệu Facebook (Giờ là META) ---
# LƯU Ý: Phải đổi "FB" thành "META"
facebook <- getSymbols("META", src = "yahoo",
return.class = "data.frame",
from = "2021-05-05",
auto.assign = FALSE)
# Xử lý dữ liệu Meta
facebook <- facebook %>%
mutate(Date = as.Date(row.names(.))) %>%
select(Date, META.Close) %>% # Cột bây giờ tên là META.Close
rename(Close = META.Close) %>%
mutate(Company = "Facebook")
# --- 3. Gộp dữ liệu ---
data_series <- rbind(apple, facebook)
# --- 4. Vẽ biểu đồ ---
ggplot(data = data_series, mapping = aes(x = Date, y = Close, color = Company)) +
geom_line(size = 1) +
scale_x_date(date_breaks = "3 month", # Chỉnh thành 3 tháng cho đỡ dày đặc
labels = date_format("%b-%Y")) +
theme_minimal() + # Thêm theme cho đẹp
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
scale_y_continuous(labels = dollar) + # Tự động format tiền tệ
labs(title = "NASDAQ Closing Prices: Apple vs Facebook (Meta)",
subtitle = "From May 2021 to Present",
caption = "Source: Yahoo Finance",
x = "",
y = "Closing Price") +
scale_color_brewer(palette = "Set1")