In this lab I will generate useful data visualization plots on
financial data by utilizing ggplot, HTML, images, emojis, and advanced
data visualization techniques within my plots. Also, I will use the
tidyverse to perform data cleaning and transformations and the ggplot
package to create visuals. The data for this project is a local file
called company_financials_csv. If interested in the code behind each
visual select the SHOW option to view.
In this section I load the needed packages, set the wd, load the
financial dataset, and perform my first few data transformations. Within
this notebook you will notice I create variations of the dataset in
objects titled d1, d1_1, and
d1_2. Select the SHOW option below to view the
code, otherwise ENJOY!
# Load the packages
pacman::p_load(tidyverse, ggtext, png, jpeg)
library(showtext)
library(sysfonts)
# Set a minimalistic theme
theme_set(theme_minimal())
# Set the WD
setwd("C:/Users/justi/OneDrive/Desktop/Grad School/UTSA 1st semester/DA 6233 - Data Analytics Visualization and Communication/Homework 2")
# Read in the data
d1 = read_csv("tnhc7nsnznjqy9gp.csv",
show_col_types = FALSE) |>
filter(saleq > 0 &
atq > 0) |>
mutate(
conm = stringr::str_to_title(conm), # Converts the string to title case
datadate = lubridate::ymd(datadate) # Convert datadate into a date variable
)
Create a bar graph showing the total assets
(atq) for each company, arranged in descending order.
d1_1 = d1 |>
group_by(conm) |>
summarize(total_assets =
sum(atq),
.groups = "drop")
d1_1 |>
ggplot(aes(
x = total_assets,
y = reorder(conm,
-total_assets))) +
geom_col() +
labs(
x = "Total Assets in $ Millions",
y = "Company") +
scale_x_continuous(
labels = scales::
label_currency())
Instructions: Enhance the plot from Q1 by adding text labels inside
the bars showing the total assets in billions (rounded to 1 decimal
place). Use hjust = 1.1, size = 3, and
fontface = "bold" for the text labels. The exact
positioning may vary slightly from the reference figure.
d1_1 |>
ggplot(aes(x = total_assets, y = reorder(conm, -total_assets))) +
geom_col() +
geom_text(aes(label = round(total_assets / 1000000, 1)), color = "white", hjust = 1.1, size = 3, fontface = "bold") +
labs(x = "Total Assets in $ Millions", y = "Company") + scale_x_continuous(labels = scales::label_currency())
Let’s explore the relationship between company size (measured by
total assets) and profitability (measured by return on assets). Create
two variables using mutate:
roa = oiadpq / atq
log_assets = log(atq)
d1_2 = d1 |>
mutate(
roa = oiadpq / atq,
log_assets =
log(atq)) |>
filter(
!is.na(roa),
!is.na(
log_assets)
)
Then create a scatter plot with log_assets on the X axis
and roa on the Y axis. Filter out any rows where
roa is NA to avoid warnings.
d1_2 |>
ggplot(
aes(
x=log_assets,
y=roa)
) +
geom_point(
shape = 21,
color = "black",
fill = "steelblue",
size = 2,
alpha = 0.7) +
geom_smooth(
method = "loess",
color = "orangered") +
labs(
x = "Log of Total Assets",
y = "Return on Assets")
Compare the asset turnover ratio (sales divided by
total assets) over time for six tech giants: Apple, Google (Alphabet),
Microsoft, Amazon, Meta, and Tesla. Use fyearq on the X
axis.
Here’s the code to prepare the data:
d1_4 = d1 |>
filter(
tic %in%
c("AAPL", "GOOGL", "MSFT", "AMZN", "META", "TSLA")) |>
mutate(
asset_turnover = saleq / atq,
fyearq_qtr = lubridate::yq(
paste(
fyearq,
fqtr,
sep = "-")
)
)
Now use d1_4 to create the following plot. Asset turnover measures how efficiently a company uses its
assets to generate sales.
d1_4 |> ggplot(
aes(
fyearq,
asset_turnover)
) +
geom_line(
color = "navyblue",
size = 1.10) +
labs(
x = "Date",
y = "Asset Turnover Ratio") +
facet_wrap(~ factor(tic,
levels =
c( "GOOGL", "AMZN", "AAPL", "META", "MSFT", "TSLA")
),
ncol = 2,
labeller = as_labeller(
c(
AAPL = "Apple Inc",
AMZN = "Amazon.com Inc",
META = "Meta Platforms Inc",
MSFT = "Micrsoft Corp",
TSLA = "Tesla Inc",
GOOGL = "Alphabet Inc")
)
)
Nvidia has experienced tremendous growth in both revenue and market capitalization. Let’s visualize these two metrics together over time.
First, create a properly formatted dataset. The last line in the code shows that the values are converted to log10. Here’s the code:
d1_5 = d1 |>
filter(conm == "Nvidia Corp") |>
mutate(mkt_cap = prccq * cshoq) |> # Create market capitalization
filter(mkt_cap > 0) |>
select(conm, datadate, mkt_cap, saleq) |>
pivot_longer(cols = c(mkt_cap, saleq),
names_to = "metric",
values_to = "value") |>
mutate(value = log10(value))
Examine d1_5 in the console using head() to
understand its structure. Then create a line plot with
datadate on the X axis.
I have used the following colors in the plot: #FF0066, #FF9A00, and #9112BC.
The Y axis plots log values. However, it is difficult for people to understand what they mean. Therefore, I am using sensible labels as you see in the plot. You will have to use log10 of these labels as your Y axis breaks. If you have difficulties, write to me.
d1_5 |>
ggplot(
aes(
x = datadate,
y = value)) +
geom_line(
aes(
color = metric),
size = 1.5,
na.rm = TRUE) +
scale_color_manual(
name = "Financial Metric",
values = c(
"mkt_cap" = "#FF0066",
"saleq" = "#FF9A00"),
labels = c(
"mkt_cap" = "Market Cap",
"saleq" = "Sales")
) +
scale_y_continuous(
breaks = c(2, 3, 4, 5, 6, log10(3000000)),
labels = function(x)
scales::label_currency()(10^x)
) +
labs(
title = "Nvidia's <span style='color:#FF0066;'>Market Cap</span> and <span style='color:#FF9A00;'>Sales</span> both surge",
subtitle = "All amounts in <span style='color:#9112BC;'>million USD</span>",
x = "Date",
y = NULL,
color = "Financial Metric"
) +
scale_x_date(date_labels = "%Y") +
theme_minimal(base_size = 14) +
theme(
legend.position = "top",
legend.title = element_text(),
legend.text = element_markdown(),
plot.title = element_markdown(size = 16),
plot.subtitle = element_markdown(size = 12)
)
Create a side-by-side bar plot comparing total annual R&D
spending (xrdq) for Apple and Microsoft starting
from 2010. Use the Lobster font from Google Fonts throughout the plot.
Set the bar colors manually to:
c("#ff6b35", "#004e89").
font_add_google("Lobster", "lobster")
showtext::showtext_auto()
d1 |>
filter(tic %in% c("AAPL", "MSFT")) |>
mutate(xrdq_scaled = xrdq * (30000 / max(xrdq, na.rm = TRUE))) |>
ggplot(aes(x = fyearq, y = xrdq_scaled, fill = tic)) +
geom_col(position = position_dodge(width = 0.8), width = 0.9) +
scale_fill_manual(
values = c("AAPL" = "#ff6b35", "MSFT" = "#004e89"),
labels = c("AAPL" = "Apple", "MSFT" = "Microsoft")
) +
scale_x_continuous(
limits = c(2009.5, 2024.5),
breaks = seq(2010, 2024, by = 1),
minor_breaks = NULL
) +
scale_y_continuous(
limits = c(0, 30000),
breaks = c(10000, 20000, 30000),
minor_breaks = seq(0, 30000, by = 5000),
labels = c("10,000", "20,000", "30,000")
) +
labs(
fill = "",
y = "R&D Spending ($ million)",
x = "Fiscal Year"
) +
theme_minimal(base_size = 14, base_family = "lobster") +
theme(
legend.position = "top",
panel.grid.major.x = element_line(color = "gray90", linewidth = 0.3),
panel.grid.major.y = element_line(color = "gray90", linewidth = 0.6),
panel.grid.minor.y = element_line(color = "gray90", linewidth = 0.3)
)
showtext::showtext_end()
Create a bar graph showing total revenue (saleq) for all
13 companies in fiscal year 2022. Use Montserrat font from Google Fonts
for the title background and Noto Sans for axis text. The title
background color is #1E93AB, the plot background color is #DCDCDC, and
bars are filled with #67C090. Add company logos for the top 3 revenue
generators using annotation_raster().
font_add_google("Montserrat", "Noto Sans")
apple_img <- png::readPNG("official-apple-logo-png.png")
alphabet_img <- png::readPNG("alphabet-logo-rotated.png")
amazon_img <- png::readPNG("Amazon_icon.png")
showtext::showtext_auto()
d1_6 <- d1 |>
filter(fyearq == 2022) |>
group_by(conm) |>
summarize(total_sale = sum(saleq, na.rm = TRUE))
d1_6 |>
ggplot(aes(x = reorder(conm, -total_sale), y = total_sale)) +
geom_col(fill = "#67C090") +
labs(
title = "Amazon leads tech giants in total revenue in 2022",
x = NULL,
y = NULL
) +
scale_y_continuous(
limits = c(0, max(500000, 1.1 * max(d1_6$total_sale))),
breaks = c(0, 100000, 200000, 300000, 400000, 500000),
minor_breaks = seq(0, 500000, by = 100000),
labels = c("0", "100,000", "200,000", "300,000", "400,000", "500,000")
) +
annotation_raster(
amazon_img,
xmin = 1 - 0.45,
xmax = 1 + 0.45,
ymin = d1_6$total_sale[1] * 1.45,
ymax = d1_6$total_sale[1] * 1.75) +
annotation_raster(
alphabet_img,
xmin = 3 - 0.4,
xmax = 3 + 0.4,
ymin = d1_6$total_sale[1] * .0,
ymax = d1_6$total_sale[1] * 1.) +
annotation_raster(
apple_img,
xmin = 2 - 0.25,
xmax = 2 + 0.25,
ymin = d1_6$total_sale[1] * 1.15,
ymax = d1_6$total_sale[1] * 1.35
) +
theme_minimal(base_size = 14, base_family = "NotoSans") +
theme(
axis.text.x = element_text(angle = 30, hjust = .7),
axis.text.y = element_text(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.background = element_rect(fill = "#DCDCDC"),
plot.title = element_textbox_simple(
size = 16,
padding = margin(5, 5, 5, 5),
fill = "#1E93AB",
color = "white",
family = "Montserrat"
)
)