Exercícios de Visualização de Dados

Questão 1

clock <- c(0.1, 0.5, 1, 1.5, 2, 2.5, 3)
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.6125810476877268)

mat <- matrix(c(1, 1,
                2, 3,
                4, 5,
                6, 0), nrow = 4, byrow = TRUE)
layout(mat)

par(mar = c(4, 4, 1, 1))

plot(clock, MRT_1F, type = "b", pch = 4, col = "black",
     xlab = "Time between Things requests (seconds)", ylab = "Response Time (sec.)",
     ylim = c(0, 550))
lines(clock, MRT_3F, type = "b", pch = 15, col = "yellow")
lines(clock, MRT_5F, type = "b", pch = 1, col = "pink")
lines(clock, MRT_10F, type = "b", pch = 2, col = "blue")
lines(clock, MRT_15F, type = "b", pch = 5, col = "purple")
lines(clock, MRT_sem_F, type = "b", pch = 3, col = "green")

legend("topright", legend = c("1 Fog", "3 Fogs", "5 Fogs", "10 Fogs", "15 Fogs", "w/o Fog"),
       col = c("black", "yellow", "pink", "blue", "purple", "green"),
       pch = c(4, 15, 1, 2, 5, 3), cex = 0.8)

plot_bars <- function(data_fog, fog_name) {
  dados <- rbind(MRT_sem_F, data_fog)
  
  barplot(dados, beside = TRUE, log = "y",
          col = c("#E6E6E6", "#666666"),
          names.arg = clock,
          xlab = "Time between Things requests",
          ylab = "Response time (s)")
          
  legend("topright", legend = c("w/o Fog", fog_name),
         fill = c("#E6E6E6", "#666666"), cex = 0.8)
}

plot_bars(MRT_1F, "1 Fog")
plot_bars(MRT_3F, "3 Fogs")
plot_bars(MRT_5F, "5 Fogs")
plot_bars(MRT_10F, "10 Fogs")
plot_bars(MRT_15F, "15 Fogs")

Questão 2

meal_data <- matrix(
  c(53.8, 33.9, 2.6, 0.0,   # Good
    43.6, 54.2, 60.5, 21.4, # Very Good
    2.6, 11.9, 36.8, 78.6), # Excellent
  nrow = 3, 
  byrow = TRUE
)

colnames(meal_data) <- c("$10-19", "$20-29", "$30-39", "$40-49")
rownames(meal_data) <- c("Good", "Very Good", "Excellent")

barplot(meal_data,
        main = "Classificação da Qualidade da Refeição por Faixa de Preço",
        xlab = "Preço da Refeição (Meal Price)",
        ylab = "Porcentagem (%)",
        col = c("#A9CCE3", "#2980B9", "#154360"),
        legend.text = rownames(meal_data),
        args.legend = list(x = "topright", inset = c(-0.05, -0.05), cex = 0.8))

Questão 3

dados_maio <- subset(airquality, Month == 5)

# Fórmula: C = (F - 32) / 1.8
temp_celsius <- (dados_maio$Temp - 32) / 1.8

hist(temp_celsius, 
     main = "Distribuição de Temperaturas no mês de Maio", 
     xlab = "Temperatura (°C)", 
     ylab = "Densidade", 
     col = "lightgreen", 
     border = "white",
     freq = FALSE)

lines(density(temp_celsius), col = "darkgreen", lwd = 2)

Questão 4

sales <- read.table("https://training-course-material.com/images/8/8f/Sales.txt", header=TRUE)

porcentagens <- round(sales$SALES / sum(sales$SALES) * 100, 1)

rotulos <- paste(porcentagens, "%", sep="")

cores <- rainbow(nrow(sales))

pie(sales$SALES, 
    labels = rotulos, 
    col = cores, 
    main = "Porcentagem do Total de Vendas por País")

legend("bottomleft", 
       legend = sales$COUNTRY, 
       fill = cores, 
       title = "Países",
       cex = 0.8)

Questão 5

boxplot(count ~ spray, data = InsectSprays,
        outline = FALSE, 
        col = "yellow",
        main = "Contagem de Insetos por Tipo de Inseticida",
        xlab = "Tipo de Inseticida (Spray)",
        ylab = "Contagem de Insetos")

Questão 6

process_data <- function(filepath) {

  df <- read.csv(filepath, stringsAsFactors = FALSE)
  
  df$currentTime <- as.POSIXct(df$currentTime)

  df$time_hours <- as.numeric(difftime(df$currentTime, df$currentTime[1], units = "hours"))

  valores <- as.numeric(gsub("[A-Za-z]+", "", df$usedMemory))

  multiplicador <- ifelse(grepl("TB", df$usedMemory), 1000000,
                   ifelse(grepl("GB", df$usedMemory), 1024,
                   ifelse(grepl("KB", df$usedMemory), 1/1024, 1)))

  df$memory_mb <- valores * multiplicador
  
  return(df)
}

df_none <- process_data("monitoringCloudData_NONE.csv")
df_01   <- process_data("monitoringCloudData_0.1.csv")
df_05   <- process_data("monitoringCloudData_0.5.csv")
df_1.0  <- process_data("monitoringCloudData_1.csv")

matriz_layout <- matrix(c(1, 2, 
                          3, 4), nrow = 2, byrow = TRUE)
layout(matriz_layout)
par(mar = c(5, 4, 4, 2) + 0.1)

plot(df_none$time_hours, df_none$memory_mb, type = "l",
     main = "Memory Analysis (None Workload)",
     xlab = "Time (hour)", ylab = "Used Memory (MB)")

plot(df_01$time_hours, df_01$memory_mb, type = "l",
     main = "Memory Analysis (Workload of 0.1)",
     xlab = "Time (hour)", ylab = "Used Memory (MB)")

plot(df_05$time_hours, df_05$memory_mb, type = "l",
     main = "Memory Analysis (Workload of 0.5)",
     xlab = "Time (hour)", ylab = "Used Memory (MB)")

plot(df_1.0$time_hours, df_1.0$memory_mb, type = "l",
     main = "Memory Analysis (Workload of 1.0)",
     xlab = "Time (hour)", ylab = "Used Memory (MB)")

Questão 7

library(plotly)

netflix <- read.csv("netflix_titles.csv", stringsAsFactors = FALSE)

netflix_um_pais <- subset(netflix, 
                          country != "" & 
                          !is.na(country) & 
                          !grepl(",", country))

contagem_paises <- as.data.frame(table(netflix_um_pais$country))
colnames(contagem_paises) <- c("Pais", "Quantidade")

contagem_ordenada <- contagem_paises[order(-contagem_paises$Quantidade), ]
top10_paises <- head(contagem_ordenada, 10)

plot_ly(top10_paises, 
        labels = ~Pais, 
        values = ~Quantidade, 
        type = 'pie',
        textinfo = 'label+percent',
        hoverinfo = 'text',
        text = ~paste(Pais, ": ", Quantidade, " conteúdos")) %>%
  layout(title = "Top 10 Países com Mais Conteúdo na Netflix (Único País de Origem)",
         showlegend = TRUE)

Questão 8

plot_ly(
  type = 'table',

  header = list(
    values = c("<b>País</b>", "<b>Total de conteúdos</b>"),
    align = 'center',                                       
    fill = list(color = 'grey'),                            
    font = list(color = 'white', size = 14),                
    line = list(width = 1, color = 'black')
  ),

  cells = list(
    values = rbind(as.character(top10_paises$Pais), top10_paises$Quantidade),
    align = 'center',                                       
    fill = list(color = 'white'),
    font = list(color = 'black', size = 12),
    line = list(width = 1, color = 'black')
  )
)

Questão 9

netflix$decada <- floor(netflix$release_year / 10) * 10

freq_decada <- as.data.frame(table(netflix$decada, netflix$type))
colnames(freq_decada) <- c("Decada", "Tipo", "Quantidade")

freq_decada$Decada <- as.numeric(as.character(freq_decada$Decada))

dados_filmes <- subset(freq_decada, Tipo == "Movie")
dados_series <- subset(freq_decada, Tipo == "TV Show")

plot_ly() %>%
  add_trace(data = dados_series, x = ~Decada, y = ~Quantidade, 
            type = 'scatter', mode = 'lines+markers',
            name = 'TV Series', 
            line = list(color = '#2980B9'), marker = list(color = '#2980B9')) %>%
            
  add_trace(data = dados_filmes, x = ~Decada, y = ~Quantidade, 
            type = 'scatter', mode = 'lines+markers',
            name = 'Movies', 
            line = list(color = '#F39C12'), marker = list(color = '#F39C12')) %>%
            
  layout(title = "Evolução da Quantidade de Conteúdo por Década",
         xaxis = list(title = "Década"),
         yaxis = list(title = "Qnt. Conteúdo"))

Questão 10

filmes_2000_2010 <- subset(netflix, type == "Movie" & release_year >= 2000 & release_year <= 2010)

filmes_2000_2010$primeiro_genero <- trimws(gsub(",.*", "", filmes_2000_2010$listed_in))

generos_alvo <- c("Dramas", "Action & Adventure", "Comedies")
dados_q10 <- subset(filmes_2000_2010, primeiro_genero %in% generos_alvo)

contagem_q10 <- as.data.frame(table(dados_q10$release_year, dados_q10$primeiro_genero))
colnames(contagem_q10) <- c("Ano", "Genero", "Quantidade")

contagem_q10$Genero <- as.character(contagem_q10$Genero)
contagem_q10$Genero[contagem_q10$Genero == "Dramas"] <- "Drama"
contagem_q10$Genero[contagem_q10$Genero == "Action & Adventure"] <- "Ação e Aventura"
contagem_q10$Genero[contagem_q10$Genero == "Comedies"] <- "Comédia"

contagem_q10$Genero <- factor(contagem_q10$Genero, levels = c("Drama", "Ação e Aventura", "Comédia"))

plot_ly(contagem_q10, 
        x = ~Ano, 
        y = ~Quantidade, 
        color = ~Genero, 
        type = 'bar',
        colors = c("#2980B9", "#F39C12", "#27AE60")) %>% 
  
  layout(barmode = 'group', 
         title = "Lançamentos de Filmes por Gênero (2000 - 2010)",
         xaxis = list(title = "Ano de Lançamento", dtick = 2), # dtick = 2 faz o eixo pular de 2 em 2
         yaxis = list(title = "Qnt. de Lançamentos"))