Exercício: Visualização de Dados

Author

Fernando de Campos Guerreiro

Exercício 1

Utilizando os dados de produção de ovos nos EUA faça um gráfico mostrando a evolução do número de ovos de galinhas criadas livres (orgânicas e não-orgânicas) ao longo dos anos.

eggproduction Use os dados de eggproduction readr::read_csv(’https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-04-11/egg-production.csv’)

Divida os valores (n_eggs ou n_hens) por 1000000 (1 milhão) para facilitar a plotagem

echo = FALSE
setwd("C:/Users/Lenovo/OneDrive - ufpr.br/Área de Trabalho/DOC_Ecologia/Visualização_R/Aulas")

library(tidyverse)
Warning: pacote 'dplyr' foi compilado no R versão 4.4.1
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── 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
eggproduction <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-04-11/egg-production.csv')
Rows: 220 Columns: 6
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (3): prod_type, prod_process, source
dbl  (2): n_hens, n_eggs
date (1): observed_month

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
str(eggproduction)
spc_tbl_ [220 × 6] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ observed_month: Date[1:220], format: "2016-07-31" "2016-08-31" ...
 $ prod_type     : chr [1:220] "hatching eggs" "hatching eggs" "hatching eggs" "hatching eggs" ...
 $ prod_process  : chr [1:220] "all" "all" "all" "all" ...
 $ n_hens        : num [1:220] 57975000 57595000 57161000 56857000 57116000 ...
 $ n_eggs        : num [1:220] 1.15e+09 1.14e+09 1.09e+09 1.13e+09 1.10e+09 ...
 $ source        : chr [1:220] "ChicEggs-09-23-2016.pdf" "ChicEggs-10-21-2016.pdf" "ChicEggs-11-22-2016.pdf" "ChicEggs-12-23-2016.pdf" ...
 - attr(*, "spec")=
  .. cols(
  ..   observed_month = col_date(format = ""),
  ..   prod_type = col_character(),
  ..   prod_process = col_character(),
  ..   n_hens = col_double(),
  ..   n_eggs = col_double(),
  ..   source = col_character()
  .. )
 - attr(*, "problems")=<externalptr> 
eggproduction <- eggproduction %>% select(-source) %>% 
  mutate(Produtividade = n_eggs/n_hens) %>% 
  separate(observed_month, into = c("year", "month", "day"),
           sep = "-")

#Gráfico 1
Grafico1 <- ggplot(data=filter(eggproduction, prod_process != "all"),
                   aes(x=year, y=n_hens/1000000, 
                       fill = prod_process)) +
  geom_boxplot() +
  facet_wrap(~prod_process, scales = "free_y") +
  labs(
    title = "Number of Hens",
    subtitle = "Per million",
    x = "Year",      
    y = "n_hens"     
  ) +
  scale_fill_brewer(palette = "paleta") +
  theme_classic() + 
  theme(axis.title = element_blank(),
        legend.position = "none",
        plot.title = element_text(hjust = 0.5),
        plot.subtitle= element_text(hjust = 0.5))
Warning: Unknown palette: "paleta"
print(Grafico1)

#Gráfico 2
Grafico2 <- ggplot(data=filter(eggproduction, prod_process != "all"),
                   aes(x=year, y=n_eggs/1000000, 
                       fill = prod_process)) +
  geom_boxplot() +
  facet_wrap(~prod_process, scales = "free_y") +
  labs(title = "Number of Eggs", subtitle = "Per million",
       x = "Year",
       y = "n_eggs") +
  scale_fill_brewer(palette = "paleta") +
  theme_classic() + 
  theme(axis.title = element_blank(),
        legend.position = "none",
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5))
Warning: Unknown palette: "paleta"
print(Grafico2)

ggsave("Grafico.jpg", Grafico1, units = "cm", width = 20, height = 15)
ggsave("Grafico1.jpg", Grafico2, units = "cm", width = 20, height = 15)

Exercício 2

Utilizando os dados de produção de ovos nos EUA faça um gráfico comparando a produtividade dos diferentes tipos de processos e dos diferentes tipos de produtos.

eggproduction Use os dados de eggproduction readr::read_csv(‘https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-04-11/egg-production.csv’)

Calcule a produtividade como a razão entre o número de galinhas e o número de ovos

echo = FALSE
library(ggridges)
Warning: pacote 'ggridges' foi compilado no R versão 4.4.1
densidade <- ggplot(eggproduction, aes(x=Produtividade, y=prod_process, fill=prod_type)) +
  geom_density_ridges(alpha=0.5) +
  scale_fill_manual(values=c("#F1EB17", "#F1172A"),
                    labels=c("Ovos Incubados",
                             "Ovos de Mesa")) +
  scale_y_discrete(expand = c(0,0),
                   labels = c(`cage-free (organic)`="Orgânico", `cage-free (non-organic)`="Não orgânico", `all`="Todos"))+
  scale_x_continuous(expand = c(0,0)) +
  labs(title = "Produtividade (ovos/galinha)",
       subtitle = "Produção orgânica se equipara a produção não orgânica") +
  theme_ridges() +
  theme(axis.title = element_blank(),
        legend.title = element_blank(),
        legend.position = c(0.2,0.85),
        panel.background = element_rect(fill = "#F0E9AD"),
        plot.background = element_rect(fill = "#F5E5C7"),
        panel.grid.major = element_blank(),
        legend.background = element_rect(fill = "#F5E3C7"))
Warning: A numeric `legend.position` argument in `theme()` was deprecated in ggplot2
3.5.0.
ℹ Please use the `legend.position.inside` argument of `theme()` instead.
print(densidade)
Picking joint bandwidth of 0.242

Exercício 3

Utilizando os dados de produção de ovos nos EUA faça um gráfico comparando a produtividade entre os meses dos anos.

eggproduction Use os dados de eggproduction readr::read_csv(‘https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-04-11/egg-production.csv’)

Calcule a produtividade como a razão entre o número de galinhas e o número de ovos

Veja a diferença entre os diferentes processos ou tipos de produtos!

echo = FALSE
library(tidyverse)
library(ggsci)
Warning: pacote 'ggsci' foi compilado no R versão 4.4.1
eggproduction <- eggproduction %>%
  mutate(Produtividade = n_eggs / n_hens)

exercicio3 <- ggplot(eggproduction, aes(x = month, y = Produtividade, fill = prod_type)) +
  geom_boxplot(alpha = 0.6, width = 0.4) +
  facet_wrap(~prod_process, ncol = 1) +
  theme_classic() +
  scale_fill_uchicago() +
  labs(
    title = "Produtividade (ovos/galinha)",
    subtitle = "Diminuição no mês de fevereiro",
    x = "Month",          
    y = "Productivity"    
  ) +
  theme(
    legend.title = element_blank(),      
    legend.position = "bottom",
  )

print(exercicio3)

Exercício 4

Utilizando os dados do projeto portal - que não é do ET Bilu faça um gráfico mostrando a relação linear entre o tamanho do pé e o peso dos roedores.

portal project Use os dados de espécies readr::read_csv(‘https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/species.csv’)

echo = FALSE
library(ggplot2)
library(readr)
library(png)
library(grid)

species <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/species.csv')
Rows: 21 Columns: 15
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (4): species, scientificname, taxa, commonname
dbl (11): censustarget, unidentified, rodent, granivore, minhfl, meanhfl, ma...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
ratinhofeliz <- png::readPNG("C:/Users/Lenovo/OneDrive - ufpr.br/Área de Trabalho/DOC_Ecologia/Visualização_R/Aulas/ratinhofeliz.png")  
ratinho_raster <- as.raster(ratinhofeliz)

Exercicio4 <- ggplot(species, aes(x=meanhfl, y=meanwgt)) +
  geom_point(alpha=0.9, color="#ADE1EE", size=4) +
  geom_smooth(method = "lm", se=F, color="#ADE1EE") +
  geom_text(label=species$scientificname, check_overlap = TRUE, fontface="italic", size = 3) +
  labs(x="Tamanho do pé (mm)", y="Peso corporal (g)", 
       title = "Relação entre peso e tamanho do pé de roedores") +
  annotate("text", label = expression(paste(r^2, "=0.53, p-value < 0.001")),
           x=45, y=15) +
  xlim(5, 55) +
  annotation_raster(ratinho_raster, xmin = 10, xmax = 20,
                    ymin = 100, ymax = 150) +
  theme_classic()

print(Exercicio4)
`geom_smooth()` using formula = 'y ~ x'
Warning in is.na(x): is.na() aplicado a um objeto diferente de lista ou vetor
de tipo 'expression'

Exercício 5

#Utilizando os dados do projeto portal compare o peso médio e o peso dos juvenis entre os diferentes gêneros.

#portal project #Use os dados de espécies readr::read_csv(‘https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/species.csv’)

library(tidyverse)
library(ggplot2)
library(readr)
library(dplyr)
especies <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/species.csv')
Rows: 21 Columns: 15
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (4): species, scientificname, taxa, commonname
dbl (11): censustarget, unidentified, rodent, granivore, minhfl, meanhfl, ma...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
pesos <- select(especies, 2, 13, 15)

sep <- pesos %>% separate(scientificname, into = c("Gênero", "epiteto"), sep = " ")
head(sep)
# A tibble: 6 × 4
  Gênero      epiteto      meanwgt juvwgt
  <chr>       <chr>          <dbl>  <dbl>
1 Baiomys     taylori         9.45   NA  
2 Chaetodipus baileyi        31.9    19.0
3 Chaetodipus hispidus       30.7    24  
4 Chaetodipus intermedius    17.5    10  
5 Chaetodipus penicillatus   17.6    11.7
6 Dipodomys   merriami       43.5    26.4
str(sep)
tibble [21 × 4] (S3: tbl_df/tbl/data.frame)
 $ Gênero : chr [1:21] "Baiomys" "Chaetodipus" "Chaetodipus" "Chaetodipus" ...
 $ epiteto: chr [1:21] "taylori" "baileyi" "hispidus" "intermedius" ...
 $ meanwgt: num [1:21] 9.45 31.87 30.72 17.47 17.62 ...
 $ juvwgt : num [1:21] NA 19 24 10 11.7 ...
resultados <- sep %>%
  group_by(Gênero) %>%
  summarise(peso_medio_geral = mean(meanwgt, na.rm = TRUE),
            peso_medio_juvenil = mean(juvwgt, na.rm = TRUE))

resultados2 <- rename(resultados, `Peso médio geral` = peso_medio_geral, `Peso médio juvenil` = peso_medio_juvenil)

resultados_long <- resultados2 %>%
  pivot_longer(cols = c(`Peso médio geral`, `Peso médio juvenil`),
               names_to = "tipo_peso",
               values_to = "peso_medio")

print(resultados_long)
# A tibble: 18 × 3
   Gênero          tipo_peso          peso_medio
   <chr>           <chr>                   <dbl>
 1 Baiomys         Peso médio geral         9.45
 2 Baiomys         Peso médio juvenil     NaN   
 3 Chaetodipus     Peso médio geral        24.4 
 4 Chaetodipus     Peso médio juvenil      16.2 
 5 Dipodomys       Peso médio geral        70.8 
 6 Dipodomys       Peso médio juvenil      44.2 
 7 Neotoma         Peso médio geral       163.  
 8 Neotoma         Peso médio juvenil      83.8 
 9 Onychomys       Peso médio geral        27.6 
10 Onychomys       Peso médio juvenil      17.0 
11 Perognathus     Peso médio geral         7.90
12 Perognathus     Peso médio juvenil       5.87
13 Peromyscus      Peso médio geral        22.2 
14 Peromyscus      Peso médio juvenil      14.0 
15 Reithrodontomys Peso médio geral        11.6 
16 Reithrodontomys Peso médio juvenil       7.15
17 Sigmodon        Peso médio geral        70.9 
18 Sigmodon        Peso médio juvenil      34.7 
plotar <- ggplot(resultados_long, aes(x = Gênero, y = peso_medio, fill = tipo_peso)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Comparação do Peso Médio Geral e dos Juvenis por Gênero",
       x = "Gênero",
       y = "Peso Médio",
       fill = "Tipo de Peso") +
  theme_classic() +
  scale_fill_manual(values = c("#CD5C5C", "#FFA07A")) +
  theme(legend.title = element_blank(),
        legend.position = "bottom",
        panel.background = element_rect(fill = "#fff1f3", color = NA),
        plot.background = element_rect(fill = "#999999", color = NA))

ggsave("Exercicio5.jpg", plotar, units = "cm", width = 20, height = 15)
Warning: Removed 1 row containing missing values or values outside the scale range
(`geom_bar()`).

Exercício 6

#Utilizando os dados do projeto portal compare o peso dos animais nos diferentes tratamentos para os diferentes sexos.

#portal project #Use os dados de surveys readr::read_csv(‘https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/surveys.csv’)

library(tidyverse)
library(readr)

surveys <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/surveys.csv')
Rows: 28364 Columns: 22
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (14): treatment, species, sex, reprod, age, testes, vagina, pregnant, n...
dbl   (7): month, day, year, plot, stake, hfl, wgt
date  (1): censusdate

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
dados_filtrados <- surveys %>%
  select(wgt, treatment, sex) %>%
  filter(!is.na(wgt), !is.na(sex))

head(dados_filtrados)
# A tibble: 6 × 3
    wgt treatment sex  
  <dbl> <chr>     <chr>
1     7 exclosure M    
2    40 control   M    
3    37 control   F    
4   117 control   F    
5    40 control   M    
6   132 control   M    
resumo_peso <- dados_filtrados %>%
  group_by(treatment, sex) %>%
  summarise(peso_medio = mean(wgt, na.rm = TRUE))
`summarise()` has grouped output by 'treatment'. You can override using the
`.groups` argument.
plot_boxplot <- ggplot(dados_filtrados, aes(x = treatment, y = wgt, fill = sex)) +
  geom_boxplot(outlier.shape = NA, position = position_dodge(width = 0.75)) +
  labs(title = "Distribuição do Peso / Tratamento e Sexo",
       x = "Tratamento",
       y = "Peso",
       fill = "Sexo") +
  theme_classic() +
  scale_fill_manual(values = c("#FF5733", "#FFC300")) +
  theme(legend.position = "bottom")

print(plot_boxplot)

ggsave("Grafico6.jpg", plot_boxplot, units = "cm", width = 20, height = 15)

Exercício 7

#Utilizando os dados do projeto portal faça um gráfico comparando a relação linear entre o tamanho do pé e o peso dos roedores para os diferentes tratamentos.

#portal project #Use os dados de surveys readr::read_csv(‘https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/surveys.csv’)

library(tidyverse)

surveys <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-05-02/surveys.csv')
Rows: 28364 Columns: 22
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (14): treatment, species, sex, reprod, age, testes, vagina, pregnant, n...
dbl   (7): month, day, year, plot, stake, hfl, wgt
date  (1): censusdate

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
dados_filtrados <- surveys %>%
  select(wgt, hfl, treatment) %>%
  filter(!is.na(wgt), !is.na(hfl))

dados_filtrados <- dados_filtrados %>%
  mutate(faixa_hfl = cut(hfl, breaks = 5))

plot_box_faixas <- ggplot(dados_filtrados, aes(x = faixa_hfl, y = wgt, fill = treatment)) +
  geom_boxplot(outlier.shape = NA, position = position_dodge(width = 0.75)) +
  labs(title = "Faixa de Tamanho do Pé e Tratamento",
       x = "Faixa de Tamanho do Pé",
       y = "Peso",
       fill = "Tratamento") +
  theme_classic() +
  scale_fill_manual(values = c("#96955f", "#c1be07", "#f2f050")) +
  theme(legend.position = "bottom")

print(plot_box_faixas)

ggsave("Grafico7.jpg", plot_box_faixas, units = "cm", width = 20, height = 15)