# Configuração global dos chunks
knitr::opts_chunk$set(echo = TRUE, # MOSTRAR o código (conforme instrução)
message = FALSE, # OCULTAR mensagens de pacotes
warning = FALSE) # OCULTAR avisos
# --- Bibliotecas ---
library(tidyverse) # Para manipulação de dados (dplyr, readr, stringr)
## Warning: pacote 'tidyverse' foi compilado no R versão 4.5.2
## Warning: pacote 'ggplot2' foi compilado no R versão 4.5.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.1 ✔ stringr 1.5.2
## ✔ ggplot2 4.0.0 ✔ tibble 3.3.0
## ✔ lubridate 1.9.4 ✔ tidyr 1.3.1
## ✔ purrr 1.1.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(plotly) # Para gráficos interativos (Questões 7-10)
## Warning: pacote 'plotly' foi compilado no R versão 4.5.2
##
## Anexando pacote: 'plotly'
##
## O seguinte objeto é mascarado por 'package:ggplot2':
##
## last_plot
##
## O seguinte objeto é mascarado por 'package:stats':
##
## filter
##
## O seguinte objeto é mascarado por 'package:graphics':
##
## layout
# --- Carregar Datasets ---
# Para Questão 4
sales <- read.csv("Sales.csv")
# Para Questão 6
#
# Função para carregar e pré-processar os dados de monitoramento
load_monitoring_data <- function(filepath) {
df <- read.csv(filepath)
# Converter currentTime para o formato POSIXct
df$currentTime <- as.POSIXct(df$currentTime, format = "%Y-%m-%d %H:%M:%OS")
# Função para converter memória para Megabytes (MB)
#
convert_to_mb <- function(mem_str) {
mem_str <- as.character(mem_str)
# Remove espaços
mem_str <- gsub(" ", "", mem_str)
if (grepl("TB", mem_str, ignore.case = TRUE)) {
# 1 TB = 1.000.000 MB
return(as.numeric(gsub("[^0-9.]", "", mem_str)) * 1000000)
} else if (grepl("GB", mem_str, ignore.case = TRUE)) {
# 1 GB = 1024 MB
return(as.numeric(gsub("[^0-9.]", "", mem_str)) * 1024)
} else if (grepl("MB", mem_str, ignore.case = TRUE)) {
return(as.numeric(gsub("[^0-9.]", "", mem_str)))
} else if (grepl("KB", mem_str, ignore.case = TRUE)) {
return(as.numeric(gsub("[^0-9.]", "", mem_str)) / 1024)
} else {
# Assume bytes se nenhuma unidade for especificada
return(as.numeric(mem_str) / (1024^2))
}
}
df$Used_Memory_MB <- sapply(df$usedMemory, convert_to_mb)
return(df)
}
# Carregar os 4 datasets
df_01 <- load_monitoring_data("monitoringCloudData/monitoringCloudData_0.1.csv")
df_05 <- load_monitoring_data("monitoringCloudData/monitoringCloudData_0.5.csv")
df_1 <- load_monitoring_data("monitoringCloudData/monitoringCloudData_1.csv")
df_none <- load_monitoring_data("monitoringCloudData/monitoringCloudData_NONE.csv")
# Calcular o tempo contínuo em horas
# Encontrar o tempo inicial (o mínimo de todos os dataframes)
start_time <- min(c(df_01$currentTime, df_05$currentTime, df_1$currentTime, df_none$currentTime), na.rm = TRUE)
# Calcular a diferença em horas para cada dataframe
df_01$Time_Hour <- as.numeric(difftime(df_01$currentTime, start_time, units = "hours"))
df_05$Time_Hour <- as.numeric(difftime(df_05$currentTime, start_time, units = "hours"))
df_1$Time_Hour <- as.numeric(difftime(df_1$currentTime, start_time, units = "hours"))
df_none$Time_Hour <- as.numeric(difftime(df_none$currentTime, start_time, units = "hours"))
# Para Questões 7-10
#
netflix_df <- read.csv("netflix_titles.csv")
# Dados fornecidos
MRT_1F <- c(517.1468515630205, 85.13094142168089, 30.333207896694553, 12.694776264558937, 3.3041601673945418, 1.1823111717498882, 1.1892293502386786)
MRT_3F <- c(156.68929936163462, 11.540837783562276, 0.4512835621696538, 0.4509797929766453, 0.4502068233039181, 0.4496185276300172, 0.4543157082191288)
MRT_5F <- c(83.90319666471157, 0.3068151086494968, 0.30522314133037304, 0.3072588968084928, 0.30655265997285697, 0.3055812715727718, 0.3053297166713006)
MRT_10F <- c(29.55430642951759, 0.19832832665772515, 0.1971923924717474, 0.19796648905716516, 0.19615594370806338, 0.2034569237883263, 0.19617420889447737)
MRT_15F <- c(11.317736530583566, 0.167364215666193, 0.16172168266811013, 0.16701085329580515, 0.1598052657153692, 0.1645934043532696, 0.16216563797118075)
MRT_sem_F <- c(11.93430909937736, 0.6095414637034009, 0.6060645101029295, 0.612167181646899, 0.6146761002685637, 0.6096747087200697, 0.61258110476877268)
clock <- c(0.1, 0.5, 1, 1.5, 2, 2.5, 3)
# --- GRÁFICO 1: Linhas ---
# Definir limite Y
ylim_max <- max(MRT_1F)
plot(clock, MRT_1F, type = "o", pch = 4, col = "black", lwd = 2,
ylim = c(0, ylim_max),
xlab = "Time between Things requests (seconds)",
ylab = "Response Time (sec.)",
main = "Response Time vs. Request Time")
# Adicionar as outras linhas
lines(clock, MRT_3F, type = "o", pch = 18, col = "red", lwd = 2)
lines(clock, MRT_5F, type = "o", pch = 1, col = "gold", lwd = 2) # Amarelo
lines(clock, MRT_10F, type = "o", pch = 17, col = "blue", lwd = 2)
lines(clock, MRT_15F, type = "o", pch = 15, col = "purple", lwd = 2)
lines(clock, MRT_sem_F, type = "o", pch = 3, col = "green", lwd = 2)
# Adicionar legenda
legend("topright",
legend = c("1 Fog", "3 Fogs", "5 Fogs", "10 Fogs", "15 Fogs", "w/o Fog"),
col = c("black", "red", "gold", "blue", "purple", "green"),
pch = c(4, 18, 1, 17, 15, 3),
lty = 1, lwd = 2, cex = 0.8, box.lty = 0)
# --- GRÁFICO 2: 5 Gráficos de Barras ---
#
# Definir layout 3x2 (espaço 6 fica vazio)
graphics::layout(matrix(c(1, 2, 3, 4, 5, 0), nrow = 3, ncol = 2, byrow = TRUE))
# Cores solicitadas
cores_barra <- c("#E6E6E6", "#666666")
# Rótulos do eixo X
nomes_clock <- as.character(clock)
# Função auxiliar para criar cada gráfico de barras
plot_barra_log <- function(data_fog, titulo) {
# Combina os dados: "sem Fog" e "com Fog"
dados_combinados <- rbind(MRT_sem_F, data_fog)
barplot(dados_combinados,
beside = TRUE,
names.arg = nomes_clock,
col = cores_barra,
log = "y", # Escala logarítmica
main = titulo,
xlab = "Time between Things requests",
ylab = "Response time (s)")
}
# Criar os 5 gráficos
plot_barra_log(MRT_1F, "w/o Fog vs 1 Fog")
legend("topright", legend = c("w/o Fog", "1 Fog"), fill = cores_barra, bty = "n")
plot_barra_log(MRT_3F, "w/o Fog vs 3 Fogs")
legend("topright", legend = c("w/o Fog", "3 Fogs"), fill = cores_barra, bty = "n")
plot_barra_log(MRT_5F, "w/o Fog vs 5 Fogs")
legend("topright", legend = c("w/o Fog", "5 Fogs"), fill = cores_barra, bty = "n")
plot_barra_log(MRT_10F, "w/o Fog vs 10 Fogs")
legend("topright", legend = c("w/o Fog", "10 Fogs"), fill = cores_barra, bty = "n")
plot_barra_log(MRT_15F, "w/o Fog vs 15 Fogs")
legend("topright", legend = c("w/o Fog", "15 Fogs"), fill = cores_barra, bty = "n")
# Resetar layout para o padrão
graphics::layout(1)
# 1. Criar a matriz de dados a partir da imagem
# Dados da tabela (coluna por coluna)
dados_q2 <- matrix(c(53.8, 43.6, 2.6, # $10-19
33.9, 54.2, 11.9, # $20-29
2.6, 60.5, 36.8, # $30-39
0.0, 21.4, 78.6), # $40-49
nrow = 3,
ncol = 4,
byrow = FALSE) # Preenchendo por coluna
# Definir nomes das linhas e colunas
rownames(dados_q2) <- c("Good", "Very Good", "Excellent")
colnames(dados_q2) <- c("$10-19", "$20-29", "$30-39", "$40-49")
# 2. Criar o gráfico de barras empilhadas
#
barplot(dados_q2,
main = "Quality Rating by Meal Price",
xlab = "Meal Price",
ylab = "Percentage (%)",
col = c("lightblue", "lightgreen", "lightyellow"), # Cores para as pilhas
legend.text = rownames(dados_q2), # Adiciona legenda
args.legend = list(x = "topright", bty = "n", inset = c(0.05, 0.05)))
# 1. Carregar o dataset (já vem no R)
data(airquality)
# 2. Filtrar dados para o mês de Maio (Month == 5) e remover NAs
temp_may_f <- airquality$Temp[airquality$Month == 5]
temp_may_f <- temp_may_f[!is.na(temp_may_f)] # Remove NAs
# 3. Converter de Fahrenheit para Celsius
#
temp_may_c <- (temp_may_f - 32) / 1.8
# 4. Gerar o histograma
#
# Usamos freq = FALSE para que o eixo Y seja densidade, permitindo sobrepor a curva
hist(temp_may_c,
main = "Histograma das Temperaturas de Maio (em Celsius)",
xlab = "Temperatura (°C)",
ylab = "Densidade",
col = "steelblue", # Cor das barras
border = "white", # Cor da borda
freq = FALSE, # Eixo Y como densidade
breaks = 10) # Número sugerido de 'bins'
# 5. Adicionar a curva de densidade
#
lines(density(temp_may_c), # Calcula a densidade
col = "darkred", # Cor da linha
lwd = 2) # Largura da linha
# 1. Agregar (somar) vendas por país
# Os nomes das colunas são COUNTRY e SALES (em maiúsculo, do CSV)
sales_by_country <- aggregate(sales$SALES, by = list(Country = sales$COUNTRY), FUN = sum)
colnames(sales_by_country) <- c("Country", "TotalSales")
# 2. Calcular a porcentagem de cada país
#
sales_by_country$Percent <- sales_by_country$TotalSales / sum(sales_by_country$TotalSales)
# Formatar para exibição
percent_labels <- scales::percent(sales_by_country$Percent, accuracy = 0.1)
pie_labels <- paste(sales_by_country$Country, "\n", percent_labels)
# 3. Definir cores
cores_pie <- rainbow(length(sales_by_country$Country))
# 4. Criar o gráfico de pizza
#
pie(sales_by_country$TotalSales,
labels = pie_labels,
col = cores_pie,
main = "Porcentagem Total de Vendas por País")
# 5. Adicionar a legenda
#
legend("topright",
legend = sales_by_country$Country,
fill = cores_pie,
cex = 0.8,
bty = "n")
# 1. Carregar o dataset (já vem no R)
data(InsectSprays)
# 2. Construir o boxplot
boxplot(count ~ spray,
data = InsectSprays,
main = "Contagem de Insetos por Tipo de Inseticida",
xlab = "Tipo de Inseticida (Spray)",
ylab = "Contagem de Insetos",
col = "yellow", # Cor de preenchimento
border = "black", # Cor da borda
outline = FALSE) # Remove os outliers
Os dados (df_01, df_05, df_1,
df_none) foram pré-carregados e pré-processados (conversão
de memória e tempo) no chunk de setup inicial.
# 1. Definir o layout para 2x2
#
graphics::layout(matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2, byrow = TRUE))
# 2. Definir margens (bottom, left, top, right) para os gráficos
par(mar = c(4.1, 4.1, 2.1, 1.1))
# --- Plot 1: None Workload ---
plot(df_none$Time_Hour, df_none$Used_Memory_MB, type = "l",
xlab = "Time (hour)",
ylab = "Used Memory (MB)",
main = "Memory Analysis (None Workload)")
# --- Plot 2: Workload of 0.1 ---
plot(df_01$Time_Hour, df_01$Used_Memory_MB, type = "l",
xlab = "Time (hour)",
ylab = "Used Memory (MB)",
main = "Memory Analysis (Workload of 0.1)")
# --- Plot 3: Workload of 0.5 ---
plot(df_05$Time_Hour, df_05$Used_Memory_MB, type = "l",
xlab = "Time (hour)",
ylab = "Used Memory (MB)",
main = "Memory Analysis (Workload of 0.5)")
# --- Plot 4: Workload of 1.0 ---
plot(df_1$Time_Hour, df_1$Used_Memory_MB, type = "l",
xlab = "Time (hour)",
ylab = "Used Memory (MB)",
main = "Memory Analysis (Workload of 1.0)")
# 3. Resetar o layout para o padrão
graphics::layout(1)
# Resetar margens
par(mar = c(5.1, 4.1, 4.1, 2.1))
O dataset netflix_df foi pré-carregado no chunk
de setup.
# 1. Filtrar conteúdos com apenas UM país de origem
#
netflix_single_country <- netflix_df %>%
filter(!grepl(",", country) & country != "" & !is.na(country))
# 2. Contar, ordenar e pegar o Top 10
country_counts <- netflix_single_country %>%
group_by(country) %>%
summarise(Total = n()) %>%
arrange(desc(Total))
top_10_countries <- head(country_counts, 10)
# 3. Criar o gráfico de pizza com Plotly
#
fig_q7 <- plot_ly(top_10_countries,
labels = ~country,
values = ~Total,
type = 'pie',
textinfo = 'label+percent',
insidetextorientation = 'radial') %>%
layout(title = 'Top 10 Países (Origem Única) com Mais Conteúdo na Netflix',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
fig_q7
Utilizaremos os dados top_10_countries preparados na
Questão 7.
# 1. Renomear colunas para a tabela
#
tabela_top_10 <- top_10_countries %>%
rename("País" = country, "Total de conteúdos" = Total)
# 2. Criar a tabela com Plotly
#
fig_q8 <- plot_ly(
type = 'table',
header = list(
values = names(tabela_top_10),
align = c('center', 'center'),
line = list(width = 1, color = 'black'),
fill = list(color = 'grey'),
font = list(size = 14, color = 'white')
),
cells = list(
values = t(as.matrix(tabela_top_10)),
align = c('center', 'center'),
line = list(color = 'black', width = 1),
fill = list(color = c('white')),
font = list(size = 12, color = 'black')
)
) %>%
layout(title = "Tabela: Top 10 Países com Mais Conteúdo na Netflix (Origem Única)")
fig_q8
# 1. Preparar os dados
#
decade_data <- netflix_df %>%
filter(!is.na(release_year) & release_year != "") %>%
# Criar a coluna "decada" (formato XXX0)
mutate(decada = floor(release_year / 10) * 10) %>%
# Agrupar e contar por decada e tipo
group_by(decada, type) %>%
summarise(Quantidade = n(), .groups = 'drop') %>%
# Filtrar para exibir décadas mais relevantes (como na imagem)
filter(decada >= 1940)
# 2. Criar o gráfico de linha com Plotly
#
fig_q9 <- plot_ly(data = decade_data,
x = ~decada,
y = ~Quantidade,
color = ~type,
type = 'scatter',
mode = 'lines+markers',
# Definir as cores manualmente
colors = c("Movie" = "orange", "TV Show" = "blue")) %>% # Amarelo/Laranja e Azul
layout(title = "Quantidade de Conteúdo por Década na Netflix",
xaxis = list(title = "Década", dtick = 20), # dtick=20 para 1940, 1960...
yaxis = list(title = "Qnd. Conteúdo"),
legend = list(title = list(text = 'Tipo')))
fig_q9
# 1. Gêneros alvo
#
generos_alvo <- c("Dramas", "Action & Adventure", "Comedies")
# 2. Preparar os dados
#
data_q10 <- netflix_df %>%
# Filtrar: Tipo "Movie", Anos 2000-2010
filter(type == "Movie" &
release_year >= 2000 &
release_year <= 2010) %>%
# Extrair o *primeiro* gênero listado
mutate(primeiro_genero = trimws(sapply(strsplit(as.character(listed_in), ","), function(x) x[1]))) %>%
# Filtrar apenas pelos gêneros alvo
filter(primeiro_genero %in% generos_alvo) %>%
# Agrupar e contar
group_by(release_year, primeiro_genero) %>%
summarise(Quantidade = n(), .groups = 'drop')
# 3. Criar o gráfico de barras lado-a-lado
#
fig_q10 <- plot_ly(data_q10,
x = ~release_year,
y = ~Quantidade,
color = ~primeiro_genero,
type = 'bar') %>%
layout(title = "Filmes Lançados por Gênero (2000-2010)",
xaxis = list(title = "Ano de Lançamento",
dtick = 2), # Ticks de 2 em 2 anos (2000, 2002...)
yaxis = list(title = "Qnt. de Lançamentos"),
barmode = 'group') # 'group' = lado-a-lado
fig_q10