Questão1

#------ Gráfico de Linhas ------
dados <- cbind(MRT_1F, MRT_3F, MRT_5F, MRT_10F, MRT_15F, MRT_sem_F)
cores <- c("black", "yellow", "red", "blue", "purple", "green")
pchs <- c(4, 11, 1, 2, 5, 4)
matplot(clock, dados, type = "o", col = cores, lty = 1, pch = pchs,
        xlab = "Time between Things requests (seconds)", ylab = "Response time (s)", main = "Questão 1")
legend("topright", legend = c("1F", "3F", "5F", "10F", "15F", "sem F"),
       col = cores, lty = 1, pch = pchs, bty = "n")

# ---- Gráficos de Barras ----
layout(matrix(1:6, ncol=2, byrow=TRUE))
cores_barras <- c("#E6E6E6", "#666666")
dados_fog <- list(
  "1 Fog" = MRT_1F,
  "3 Fogs" = MRT_3F,
  "5 Fogs" = MRT_5F,
  "10 Fogs" = MRT_10F,
  "15 Fogs" = MRT_15F
)
for (nome in names(dados_fog)) {
  valores <- rbind(MRT_sem_F, dados_fog[[nome]])
  
  barplot(valores, beside=TRUE, col=cores_barras, log="y",
          names.arg=clock,
          ylim = c(0.1, max(MRT_1F)),
          xlab = "Time between Things requests",
          ylab = "Response time (s)",
          main = nome)
  
  legend("topright", legend = c("w/o Fog", nome),
         fill = cores_barras, bty = "n")
}
plot.new()

Questão2

# ---- Gráficos de Barras Empilhadas ----
ratings <- matrix(c(
  53.8, 33.9, 2.6, 0.0,      
  43.6, 54.2, 60.5, 21.4,    
  2.6, 11.9, 36.8, 78.6      
), 
nrow = 3, byrow = TRUE)
rownames(ratings) <- c("Good", "Very Good", "Excellent")
colnames(ratings) <- c("$10–19", "$20–29", "$30–39", "$40–49")
cores <- c("lightblue", "skyblue3", "navy")
barplot(ratings,
        col = cores,
        legend.text = rownames(ratings),
        beside = FALSE, 
        main = "Classificação da Qualidade por Faixa de Preço",
        xlab = "Faixa de Preço",
        ylab = "Percentual (%)")

Questão3

# ---- Histograma ----
data("airquality")
maio <- subset(airquality, Month == 5)
temp_celsius <- (maio$Temp - 32) / 1.8
hist(temp_celsius,
     probability = TRUE,          
     col = "skyblue",             
     main = "Histograma das Temperaturas de Maio (°C)",
     xlab = "Temperatura (°C)",
     ylab = "Densidade")
lines(density(temp_celsius, na.rm = TRUE), 
      col = "red", 
      lwd = 2)

Questão4

# ---- Gráficos de Pizza ----
sales <- read.delim("https://training-course-material.com/images/8/8f/Sales.txt")
sales_total <- aggregate(SALES ~ COUNTRY, data = sales, sum)
percent <- round(100 * sales_total$SALES / sum(sales_total$SALES), 1)
labels <- paste(sales_total$COUNTRY, "-", percent, "%")
cores <- rainbow(length(sales_total$COUNTRY))
pie(sales_total$SALES,
    labels = labels,
    col = cores,
    main = "Distribuição de Vendas por País")
legend("topright", legend = sales_total$COUNTRY, fill = cores, bty = "n")

Questão5

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

Questão6

Questão7

# ---- Gráficos de Pizza ----
url <- "https://www.dropbox.com/scl/fi/vjlgt50835d6snk03add2/netflix_titles.csv?rlkey=rzrveurxlom9cjp51nbv4w1gw&dl=1"
df <- read.csv(url, stringsAsFactors = FALSE)
head(df)
##   show_id    type title          director
## 1      s1 TV Show    3%                  
## 2      s2   Movie  7:19 Jorge Michel Grau
## 3      s3   Movie 23:59      Gilbert Chan
## 4      s4   Movie     9       Shane Acker
## 5      s5   Movie    21    Robert Luketic
## 6      s6 TV Show    46       Serdar Akar
##                                                                                                                                                                         cast
## 1 João Miguel, Bianca Comparato, Michel Gomes, Rodolfo Valente, Vaneza Oliveira, Rafael Lozano, Viviane Porto, Mel Fronckowiak, Sergio Mamberti, Zezé Motta, Celso Frateschi
## 2                                                                                   Demián Bichir, Héctor Bonilla, Oscar Serrano, Azalia Ortiz, Octavio Michel, Carmen Beato
## 3                                                               Tedd Chan, Stella Chung, Henley Hii, Lawrence Koh, Tommy Kuan, Josh Lai, Mark Lee, Susan Leong, Benjamin Lim
## 4                            Elijah Wood, John C. Reilly, Jennifer Connelly, Christopher Plummer, Crispin Glover, Martin Landau, Fred Tatasciore, Alan Oppenheimer, Tom Kane
## 5            Jim Sturgess, Kevin Spacey, Kate Bosworth, Aaron Yoo, Liza Lapira, Jacob Pitts, Laurence Fishburne, Jack McGee, Josh Gad, Sam Golzari, Helen Carey, Jack Gilpin
## 6                            Erdal Beşikçioğlu, Yasemin Allen, Melis Birkan, Saygın Soysal, Berkan Şal, Metin Belgin, Ayça Eren, Selin Uludoğan, Özay Fecht, Suna Yıldızoğlu
##         country        date_added release_year rating  duration
## 1        Brazil   August 14, 2020         2020  TV-MA 4 Seasons
## 2        Mexico December 23, 2016         2016  TV-MA    93 min
## 3     Singapore December 20, 2018         2011      R    78 min
## 4 United States November 16, 2017         2009  PG-13    80 min
## 5 United States   January 1, 2020         2008  PG-13   123 min
## 6        Turkey      July 1, 2017         2016  TV-MA  1 Season
##                                                  listed_in
## 1   International TV Shows, TV Dramas, TV Sci-Fi & Fantasy
## 2                             Dramas, International Movies
## 3                      Horror Movies, International Movies
## 4 Action & Adventure, Independent Movies, Sci-Fi & Fantasy
## 5                                                   Dramas
## 6          International TV Shows, TV Dramas, TV Mysteries
##                                                                                                                                             description
## 1              In a future where the elite inhabit an island paradise far from the crowded slums, you get one chance to join the 3% saved from squalor.
## 2  After a devastating earthquake hits Mexico City, trapped survivors from all walks of life wait to be rescued while trying desperately to stay alive.
## 3 When an army recruit is found dead, his fellow soldiers are forced to confront a terrifying secret that's haunting their jungle island training camp.
## 4     In a postapocalyptic world, rag-doll robots hide in fear from dangerous machines out to exterminate them, until a brave newcomer joins the group.
## 5       A brilliant group of students become card-counting experts with the intent of swindling millions out of Las Vegas casinos by playing blackjack.
## 6 A genetics professor experiments with a treatment for his comatose sister that blends medical and shamanic cures, but unlocks a shocking side effect.
df_unico_pais <- df %>%
  filter(!is.na(country)) %>%                         
  filter(str_count(country, ",") == 0) %>%          
  filter(str_detect(country, "^[A-Za-z ]+$"))
top_paises <- df_unico_pais %>%
  count(country, sort = TRUE) %>%
  slice_max(order_by = n, n = 10)
top_paises
##           country    n
## 1   United States 2555
## 2           India  923
## 3  United Kingdom  397
## 4           Japan  226
## 5     South Korea  183
## 6          Canada  177
## 7           Spain  134
## 8          France  115
## 9           Egypt  101
## 10         Mexico  100
## 11         Turkey  100
plot_ly(
  data = top_paises,
  labels = ~country,
  values = ~n,
  type = 'pie',
  textinfo = 'label+percent',
  insidetextorientation = 'radial'
) %>%
  layout(title = "Top 10 Países com Mais Conteúdo na Netflix (Apenas 1 País de Origem)")

Questão8

# ---- Tabela ----
plot_ly(
  type = 'table',
  header = list(
    values = c("País", "Total de conteúdos"),
    align = 'center',
    fill = list(color = 'gray'),
    font = list(color = 'white', size = 14)
  ),
  cells = list(
    values = list(top_paises$country, top_paises$n),
    align = 'center',
    fill = list(color = 'white'),
    font = list(color = 'black', size = 12)
  )
)

Questão9

# ---- Gráficos de Linha ----
df_valid <- df %>%
  filter(!is.na(release_year), !is.na(type)) %>%
  mutate(release_year = as.numeric(release_year)) %>%
  filter(release_year >= 1940)
df_valid <- df_valid %>%
  mutate(decade = floor(release_year / 10) * 10)
conteudo_por_decada <- df_valid %>%
  count(decade, type)
filmes <- conteudo_por_decada %>% filter(type == "Movie")
series <- conteudo_por_decada %>% filter(type == "TV Show")
plot_ly() %>%
  add_trace(
    data = series,
    x = ~decade, y = ~n,
    type = 'scatter', mode = 'lines+markers',
    name = 'TV Series',
    line = list(color = 'blue')
  ) %>%
  add_trace(
    data = filmes,
    x = ~decade, y = ~n,
    type = 'scatter', mode = 'lines+markers',
    name = 'Movies',
    line = list(color = 'orange')
  ) %>%
  layout(
    title = "Quantidade de Conteúdos por Década",
    xaxis = list(title = "Década"),
    yaxis = list(title = "Qtd. Conteúdo")
  )

Questão10

# ---- Gráficos de Barras Lado a Lado ----
filmes <- df %>%
  filter(type == "Movie", !is.na(release_year), release_year >= 2000, release_year <= 2010) %>%
  filter(!is.na(listed_in))
filmes <- filmes %>%
  mutate(genero = str_trim(str_extract(listed_in, "^[^,]+")))
generos_desejados <- c("Dramas", "Action & Adventure", "Comedies")
filmes_filtrados <- filmes %>%
  filter(genero %in% generos_desejados)
contagem <- filmes_filtrados %>%
  count(release_year, genero) %>%
  tidyr::pivot_wider(names_from = genero, values_from = n, values_fill = 0)
plot_ly(contagem, x = ~release_year) %>%
  add_bars(y = ~Dramas, name = "Drama", marker = list(color = 'blue')) %>%
  add_bars(y = ~`Action & Adventure`, name = "Ação e Aventura", marker = list(color = 'orange')) %>%
  add_bars(y = ~Comedies, name = "Comédia", marker = list(color = 'green')) %>%
  layout(
    barmode = 'group',
    title = "Filmes por Gênero (2000-2010)",
    xaxis = list(title = "Ano"),
    yaxis = list(title = "Qtd. de Lançamentos"),
    legend = list(x = 0.8, y = 1)
  )