Graphs

Página com arquivo do script em RMarkdown

Hexagon PackageCute Penguins

# Packages
library(tidyverse)
library(remotes)
library(ggplot2)
library(RColorBrewer) #RColorBrewer::display.brewer.all()
library(showtext)
library(sysfonts)
font_add_google("Playfair Display", "Playfair") ## name of Google font, name that will be used in R
font_add_google("Bangers", "Bangers")
font_add_google("Merriweather", "Merriweather")
font_add_google("Lato", "Lato")
showtext_auto()
library(plyr) #ddply
library(dplyr) #mutate
library(ggdist) #violin
library(UpSetR) # upset graph
library(Hmisc) #montar matriz de correlação
library(ggcorrplot) #montar gráficos da matriz de correlação
library(reshape2) #melt - heatmap
library(plotly)
library(devtools)
#devtools::install_github("ipeaGIT/geobr", subdir = "r-package")
library(geobr) #mapa brazil

The palmerpenguins package contains two datasets with 344 penguins.

There are 3 different species of penguins in this dataset, collected from 3 islands in the Palmer Archipelago, Antarctica. The first dataset (penguins) is the simplified version of the raw data, and the second dataset (penguins_raw) contains all the variables and original names. Most graphs will be done using the simplified version.

# Penguin Dataset
# remotes::install_github("allisonhorst/palmerpenguins")
library(palmerpenguins)

# Getting the 2 datasets from the package to the global environment
penguins <- penguins # ?penguins for more information
penguins_raw <- penguins_raw # ?penguins_raw for more information

Bar Graphs

(N) Basic

(penguins %>% # Dataset
    ggplot(aes(sex)) + # Coluna de interesse 
    geom_bar()) # Formato de barras

(N) Complete

(penguins %>% drop_na(sex) %>% # Remove os NAs
    ggplot(aes(sex)) + # Coluna de interesse
    geom_bar(aes(y = ..count.., fill = factor(..x..)), stat="count", position = 'dodge', width = .7) + # Estética das barras e eixo y com frequência absoluta
    geom_text(aes(label = ..count..),stat= "count", vjust = -0.3, hjust = 0.4, size = 3, family="Lato", fontface = "bold") + # texto em cima das barras
    theme_bw()+
    theme(legend.position = "none", # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Bar Graph", # Título, subtítulo e títulos dos eixos
         subtitle = "Sex",
         x = "Sex", 
         y = "Absolute Frequency (N)") + 
    scale_fill_brewer(palette="Set1") + # Cor das barras
    scale_color_brewer(palette="Set1")) + # Cor do contorno das barras
    scale_x_discrete(labels= c("Female", "Male")) # Renomeando texto no eixo x

(N) Separated by groups

(penguins %>% drop_na(sex) %>% # Remove os NAs
    ggplot(aes(sex)) + # Coluna de interesse
    geom_bar(aes(y = ..count.., fill = factor(..x..)), stat="count", position = 'dodge', width = .7) + # Estética das barras e eixo y com frequência absoluta
    geom_text(aes(label = ..count..),stat= "count", vjust = -0.3, hjust = 0.4, size = 3, family="Lato", fontface = "bold") + # texto em cima das barras
    theme_bw()+
    theme(legend.position = "none", # Formatação dos textos e eixos
          strip.text = element_text(size=12, color="white", family="Bangers"), 
          strip.background = element_rect (fill="gray24"),
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Bar Graph", # Título, subtítulo e títulos dos eixos
         subtitle = "Sex by Species",
         x = "Sex", 
         y = "Absolute Frequency (N)") + 
     scale_fill_brewer(palette="Set1") + # Cor das barras
     scale_color_brewer(palette="Set1") + # Cor do contorno das barras
     scale_x_discrete(labels= c("Female", "Male"))+ # Renomeando texto no eixo x
     facet_wrap(~species, nrow = 1, labeller = labeller (Group = labels))) # Segunda variável separando o gráfico em mais gráficos

(%) Basic

(penguins %>% drop_na(sex) %>% 
    ggplot(aes(sex)) +
    geom_bar(aes(y = (..count..)/sum(..count..))))

(%) Complete

(penguins %>% drop_na(sex) %>% # Remove os NAs
    ggplot(aes(sex)) + # Coluna de interesse
    geom_bar(aes(y = (..count..)/sum(..count..), fill = factor(..x..)), stat="count", position = 'dodge', width = .7) + # Estética das barras e eixo y com frequência relativa
    geom_text(aes(label = scales::percent(round((..count..)/sum(..count..), 3)), y = (..count..)/sum(..count..)), stat= "count", vjust = -0.3, hjust = 0.4, size = 3, family="Lato", fontface = "bold") +  # texto em cima das barras
    scale_y_continuous(labels=scales::percent_format(accuracy = 1), limits = c(0,1)) + # Transformar o eixo y em porcentagem e criar limites
    theme_bw()+
    theme(legend.position = "none", # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Bar Graph", # Título, subtítulo e títulos dos eixos
         subtitle = "Sex",
         x = "Sex", 
         y = "Relative Frequency (%)") + 
    scale_fill_brewer(palette="Set1") + # Cor das barras
    scale_color_brewer(palette="Set1")) + # Cor do contorno das barras
    scale_x_discrete(labels= c("Female", "Male")) # Renomeando texto no eixo x

(%) Separated by groups

(penguins %>% drop_na(sex) %>% # Remove os NAs
    ggplot(aes(sex, group = species)) + # Coluna de interesse
    geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count", position = 'dodge', width = .7) + # Estética das barras e eixo y com frequência relativa
    geom_text(aes(label = scales::percent(round(..prop.., 3)), y = ..prop..), stat= "count", vjust = -0.3, hjust = 0.4, size = 3, family="Lato", fontface = "bold") +  # texto em cima das barras
    scale_y_continuous(labels=scales::percent_format(accuracy = 1), limits = c(0,1)) + # Transformar o eixo y em porcentagem e criar limites
    theme_bw()+
    theme(legend.position = "none", # Formatação dos textos e eixos
          strip.text = element_text(size=12, color="white", family="Bangers"), 
          strip.background = element_rect (fill="gray24"),          
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Bar Graph", # Título, subtítulo e títulos dos eixos
         subtitle = "Sex by Species",
         x = "Sex", 
         y = "Relative Frequency (%)") + 
    scale_fill_brewer(palette="Set1") + # Cor das barras
    scale_color_brewer(palette="Set1")) + # Cor do contorno das barras
    scale_x_discrete(labels= c("Female", "Male"))+ # Renomeando texto no eixo x 
    facet_wrap(~species, nrow = 1, labeller = labeller (Group = labels)) # Segunda variável separando o gráfico em mais gráficos

Histogram

Basic

(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(x = flipper_length_mm)) + 
    geom_histogram())

Complete

(penguins %>% drop_na(flipper_length_mm) %>%  # remover NAs
    ggplot(aes(x = flipper_length_mm)) + # variável quantitativa para o eixo x
    geom_histogram(alpha=1, position = "identity", color="black", fill="firebrick", bins = 20) + # bins é a quantidade de colunas
    theme_bw()+
    theme(legend.position = "none", # Formatação dos textos e eixos
          strip.text = element_text(size=12, color="white", family="Bangers"), 
          strip.background = element_rect (fill="gray24"),          
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Histogram", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length",
         x = "Flipper Length (mm)", 
         y = 'Absolute Frequency (N)'))

Separated by groups

(penguins %>% drop_na(flipper_length_mm) %>% # remover NAs
    ggplot(aes(x = flipper_length_mm, fill=species)) + # variável quantitativa para o eixo x
    geom_histogram(alpha=0.4, position = "identity", color="black", bins = 20) + # alpha muda densidade da cor, bins é a quantidade de colunas
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"),# Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_fill_brewer(palette = "Set1")+ # Cor das barras
    labs(title = "Histogram", # Título, subtítulo, legenda e eixos
         subtitle = "Flipper Length by Species",
         x = "Flipper Length (mm)", 
         y = "Absolute Frequency (N)",
         fill = "Species"))

Density Plot

Basic

penguins %>% 
    ggplot(aes(flipper_length_mm))+
    geom_density()

Complete

(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(flipper_length_mm)) + 
    geom_density(alpha=1, fill = "firebrick")+ #cor e densidade do gráfico
    geom_vline(aes(xintercept=mean(flipper_length_mm, na.rm=TRUE)), color="black", linetype="dashed", size=1)+ #linha da média
    theme_bw()+
    theme(legend.position = "none", # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Density Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length",
         x = "Flipper Length (mm)", 
         y = 'Density'))

Separated by groups

mean <- ddply(penguins, "species", summarise, grp.mean=mean(flipper_length_mm, na.rm=TRUE))
(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(flipper_length_mm, group=species, fill=species)) + 
    geom_density(alpha=0.6)+ #densidade do gráfico
    geom_vline(data=mean, aes(xintercept=grp.mean, color = species),linetype="dashed", size=1, show.legend = FALSE)+ #linha da média
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_fill_brewer(palette = "Set1")+ # Cor das curvas
    scale_color_brewer(palette = "Set1")+
    labs(title = "Density Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length by Species",
         x = "Flipper Length (mm)", 
         y = "Density",
         fill = "Species"))

Histogram with Density Plot

mean <- ddply(penguins, "species", summarise, grp.mean=mean(flipper_length_mm, na.rm=TRUE))
(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(flipper_length_mm, group=species, fill=species)) + 
    geom_histogram(aes(y=..density..), alpha=0.5, position = "identity", color="black", bins = 20) + # alpha muda densidade da cor, bins é a quantidade de colunas
    geom_density(alpha=0.3)+ #cor e densidade do gráfico
    geom_vline(data=mean, aes(xintercept=grp.mean, color = species),linetype="dashed", size=1, show.legend = FALSE)+ #linha da média
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_fill_brewer(palette = "Set1")+ # Cor das curvas
    scale_color_brewer(palette = "Set1")+
    labs(title = "Histogram with Density Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length by Species",
         x = "Flipper Length (mm)", 
         y = "Density",
         fill = "Species"))

Pie Chart

Basic

# o ggplot não tem uma função específica direito para fazer piechart, então é um pouco remendado
# Não consegui adicionar de uma forma boa os números no gráfico
(penguins %>% 
    group_by(species) %>% # separação nos grupos de espécies
    dplyr::summarise(N = n()) %>% # N = contagem das espécies
    ggplot(aes(x = "", y = N, fill = species)) +
    geom_col(width = 1) + # utilizamos um bar graph que vai ser arredondado para virar o pie chart
    coord_polar(theta = "y", start = 0)) # função utilizada para montar pie chart

Complete

(penguins %>% 
    dplyr::mutate(n_all = n()) %>% # n_all = soma de todas contagens únicas
    group_by(species) %>% # separação nos grupos de espécies
    dplyr::summarise(N = n() / unique(n_all)) %>% # N = contagem das espécies / total de contagens únicas
    ggplot(aes(x = "", y = N, fill = species)) +
    geom_col(width = 1) +
    #geom_text(aes(label = paste0(round (N*100,2), "%")), position = position_stack(vjust = 0.5), color="white", fontface="bold") +
    coord_polar(theta = "y", start = 0)+ # função utilizada para montar pie chart
    labs(title = "Pie Chart", # Título, subtítulo, legenda e eixos
         subtitle = "Species",
         x = "", 
         y = "Proportion of each species",
         fill = "Species")+
    scale_fill_brewer(palette = "Set1")+ # cor de cada grupo
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"),# Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"),
          axis.ticks = element_blank(),
          panel.grid = element_blank()))

Boxplot

Basic

penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(x = species, y = flipper_length_mm))+
    geom_boxplot()

Complete

(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(x = species, y = flipper_length_mm)) +
    geom_boxplot(aes(color = species), width = 0.5, show.legend = FALSE) + # estética dos box plots
    geom_jitter(aes(color = species), alpha = 0.7, show.legend = FALSE, position = position_jitter(width = 0.2, seed = 0)) + # estética das bolinhas (jitter)
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_color_brewer(palette = "Set1")+ # Cor dos box plots
    labs(title = "Box Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length by Species",
         x = "Species", 
         y = "Flipper Length (mm)",
         fill = "Species"))

Raincloud Plot

penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(x=species, y=flipper_length_mm))+
    ggdist::stat_halfeye(aes(fill = species), alpha = 0.4, show.legend = FALSE, adjust = .5, width = .6, .width = 0, justification = -.3) + 
    geom_boxplot(aes(color = species), width = 0.25,show.legend = FALSE, outlier.shape = NA) + # estética dos box plots
    geom_jitter(aes(color = species), alpha = 0.4, position = position_jitter(width = 0.1, seed = 0)) +
    #geom_point(size = 1.3, alpha = .3, position = position_jitter(seed = 1, width = .1))+
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_color_brewer(palette = "Set1")+ # Cor dos box plots
    scale_fill_brewer(palette = "Set1")+ # Cor dos box plots
    labs(title = "Raincloud Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length by Species",
         x = "Species", 
         y = "Flipper Length (mm)",
         color = "Species")+
    guides(color = guide_legend(override.aes = list(size = 5)))+
    coord_cartesian(xlim = c(1.2, NA), clip = "off")

Scatter Plot

Basic

(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(flipper_length_mm, bill_length_mm))+
    geom_point())

Complete

(penguins %>% drop_na(flipper_length_mm, bill_length_mm) %>% 
    ggplot(aes(flipper_length_mm, bill_length_mm))+
        geom_point(color="firebrick", size = 2, alpha = 1) +    
        geom_smooth(method = "lm", se = FALSE, color="dodgerblue4") +
        theme_bw()+
        theme(legend.position = "none", # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    labs(title = "Scatter Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length x Bill Length",
         x = "Flipper Length (mm)", 
         y = "Bill Length (mm)"))

Separated by Species

(penguins %>% drop_na(flipper_length_mm, bill_length_mm) %>% 
    ggplot(aes(flipper_length_mm, bill_length_mm))+
        geom_point(aes(color=species, shape=species), size = 2, alpha = 1) +    
        geom_smooth(method = "lm", se = FALSE, aes(color = species)) +
        theme_bw()+
        theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
        scale_color_brewer(palette = "Set1")+ # Cor dos box plots
        scale_fill_brewer(palette = "Set1")+ # Cor dos box plots
        labs(title = "Scatter Plot", # Título, subtítulo e títulos dos eixos
             subtitle = "Flipper Length x Bill Length by Species",
             x = "Flipper Length (mm)", 
             y = "Bill Length (mm)",
             color = "Species",
             shape = "Species"))

Upset Plot (without ggplot2)

# precisamos de 1 coluna para cada variávei, deixo em formato 0/1 geralmente
upset_pengu <- as.data.frame(penguins)
upset_pengu$ID <- paste0("Pingu", 1:344)
upset_pengu$Adelie <- as.integer(if_else(upset_pengu$species=="Adelie",1,0))
upset_pengu$Chinstrap <- as.integer(if_else(upset_pengu$species=="Chinstrap",1,0))
upset_pengu$Gentoo <- as.integer(if_else(upset_pengu$species=="Gentoo",1,0))
upset_pengu$Biscoe <- as.integer(if_else(upset_pengu$island=="Biscoe",1,0))
upset_pengu$Dream <- as.integer(if_else(upset_pengu$island=="Dream",1,0))
upset_pengu$Torgersen <- if_else(upset_pengu$island=="Torgersen",1,0)
upset_pengu <- upset_pengu[,c(9:15)]

upset(upset_pengu, # dataset
      order.by = c("freq","degree"), #freq = contagem; degree = individual, combinação de 2, combinação de 3...
      decreasing = c(T,F), # order decrescente para frequencia, e crescente para grau
      nset=6, # número de variáveis
      nintersects = NA, # número de intersecções (NA = sem limites)
      sets.bar.color=c("maroon","blue","orange","red4","aquamarine4", "purple4"), # cores de cada barra horizontal
      keep.order = T, # manter a ordem definida em "sets"
      sets = c("Adelie", "Chinstrap", "Gentoo", "Biscoe", "Dream", "Torgersen"), # definir as colunas da tabela
      matrix.color = "black", #cor das bolinhas e linhas
      # main.bar.color=brewer.pal(5,"Set1"), # cor do gráfico de barras
      mainbar.y.label = "Counts", #label do eixo y
      text.scale = 1.3) # tamanho de toda fontes (palavras e números)

Correlation Matrix

# Usando outro dataset com mais variáveis numéricas
data(mtcars)

# Gerando matrix de correlação de spearman e p-valores
matrix <- rcorr(as.matrix(mtcars), type = c("spearman"))
matrix$P[is.na(matrix$P)] <- 0

ggcorrplot::ggcorrplot(matrix$r, #a matriz a ser visualizada
                       #type = "lower", #mostra só a parte de baixo
                       #type = "upper", #mostra só a parte de cima
                       #hc.order = TRUE, #coloca em ordem
                       #method = "circle", #muda para círculos 
                       lab = TRUE, # plota os números
                       lab_size = 2, # regula o tamanho do número
                       digits = 2, #casas depois da vírgula
                       insig = "blank",  #deixa branco o que não tem correlação significativa
                       p.mat = matrix$P,  #mostra o que não tem correlação significativa com X bem grande, ou em branco se insig = "blank
                       colors = c("blueviolet", "white", "firebrick"), #altera cores
                       outline.color = "white",
                       legend.title = "Spearman\nCorrelation\n",
                       tl.cex = 8)+
    theme(legend.title = element_text(size=10, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=17, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.text = element_text(family = "Lato", color="black", face="bold"))+
    labs(title = "Correlation Matrix", # Título, subtítulo e títulos dos eixos
         subtitle = "Spearman")

Heatmap

# Usando outro dataset com mais variáveis numéricas
data(mtcars) 

# Manipulando data frame 
mtcars_scale <- data.frame(scale(mtcars)) # normalizar valores
mtcars_scale$model <- rownames(mtcars_scale) # cria coluna com "row.names"
mtcars_melt <- melt(mtcars_scale, id.vars = "model") # tranpõe toda tabela mantendo como fixo o id.vars

(mtcars_melt %>% 
    ggplot(aes(x = variable, y = model)) + 
    geom_tile(aes(fill = value), color = "white", size = 1) + 
    scale_fill_gradient(low = "gray95", high = "firebrick1") + 
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          axis.ticks = element_blank(), 
          panel.background = element_blank(),
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 10, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 7, face="bold"))+
    labs(title = "Heatmap", # Título, subtítulo e títulos dos eixos
         subtitle = "Car Models",
         x = "Characteristics", 
         y = "Car Models",
         fill = "Values"))

Plotly (Interactive Graphs)

Converting ggplot2 graph into plotly graph (interactive).

It loses some of the aesthetic editing but allow you to explore the data in the chart. It can be used in any kind of graph but I usually prefer to use in box plots, scatter plots, heatmaps and maps.

We can also change the mouseover data and add subtitles with some workaround.

#Box Plot
ggplotly(penguins %>% drop_na(flipper_length_mm) %>% 
    ggplot(aes(x = species, y = flipper_length_mm)) +
    geom_boxplot(aes(color = species), width = 0.5, show.legend = FALSE) + # estética dos box plots
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_color_brewer(palette = "Set1")+ # Cor dos box plots
    labs(title = "Box Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length by Species",
         x = "Species", 
         y = "Flipper Length (mm)",
         fill = "Species")) %>% 
    layout(title = list(text = paste0('<b>','Box Plot','<b>',
                                    '<br>',
                                    '<sup>','Flipper Length by Species', '</sup>')))
#Scatter Plot
ggplotly(penguins_raw %>% drop_na(`Flipper Length (mm)`, `Culmen Length (mm)`) %>% 
    ggplot(aes(`Flipper Length (mm)`, `Culmen Length (mm)`))+
    geom_point(aes(color=Species, shape=Species, text = paste("Individual ID: ", `Individual ID`, "\n", "Species: ", Species, sep = ""), color = "white", size = 1), size = 2, alpha = 1, show.legend = FALSE) +    
    geom_smooth(method = "lm", se = FALSE, aes(color = Species), show.legend = FALSE) +
    theme_bw()+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
      plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
      plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
      axis.title = element_text(family = "Lato", color="black", size = 12, face="bold"),
      axis.text = element_text(family = "Lato", color="black", size = 10, face="bold"))+
    scale_color_brewer(palette = "Set1")+ # Cor dos box plots
    scale_fill_brewer(palette = "Set1")+ # Cor dos box plots
    labs(title = "Scatter Plot", # Título, subtítulo e títulos dos eixos
         subtitle = "Flipper Length x Bill Length by Species",
         x = "Flipper Length (mm)", 
         y = "Culmen Length (mm)",
         color = "Species",
         shape = "Species"),
    tooltip = "text") %>%   
    layout(title = list(text = paste0('<b>','Scatter Plot','<b>',
                                    '<br>',
                                    '<sup>','Flipper Length x Culmen Length by Species', '</sup>')),
           showlegend=FALSE)
#Heatmap
ggplotly(mtcars_melt %>% 
    ggplot(aes(x = variable, y = model)) + 
    geom_tile(aes(fill = value, text = paste("Value: ", round(value,2), "\n", sep = ""), color = "white", size = 1)) + 
    scale_fill_gradient(low = "gray95", high = "firebrick1") + 
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          axis.ticks = element_blank(), 
          panel.background = element_blank(),
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 10, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 7, face="bold"))+
    labs(title = "Heatmap", # Título, subtítulo e títulos dos eixos
         subtitle = "Car Models",
         x = "Characteristics", 
         y = "Car Models",
         fill = "Values"),
    tooltip = "text") %>%   
    layout(title = list(text = paste0('<b>','Heatmap','<b>',
                                    '<br>',
                                    '<sup>','Car Models', '</sup>')))

Maps (Brazil)

br <- read_state(code_state="all", year = 2020, showProgress = FALSE)#pegando mapa com todos os estados do Brasil

#br_df <- merge(br,df, by.x = "abbrev_state", by.y = "col_abbrev_state", all.x = TRUE) #merge com dataset de interesse
#br_df$value[is.na(br_pumas$value)] <- 0

br$value <- runif(27, 1, 99) # não tenho dataset, então só gerei uns números aleatórios

ggplotly(br %>% 
    ggplot()+
    geom_sf(aes(fill=value, text = paste("State: ", name_state , "\n" ,"Value: ", round(value,1), sep = "")))+
    scale_fill_gradient(low = "gray95", high = "dodgerblue4")+
    theme(legend.title = element_text(size=12, color="Black", family="Merriweather", face="bold.italic"), # Formatação dos textos e eixos
          plot.title = element_text(family = "Playfair", color="black", size=20, face="bold.italic"),
          plot.subtitle = element_text(family = "Merriweather", color="gray24", size=12, face="bold.italic"),
          axis.title = element_text(family = "Lato", color="black", size = 10, face="bold"),
          axis.text = element_text(family = "Lato", color="black", size = 7, face="bold"))+
    labs(title = "Brazil Map", # Título, subtítulo e títulos dos eixos
         fill = "Values"),
    tooltip = "text") %>%   
    layout(title = list(text = paste0('<b>','Brazil Map','<b>',
                                    '<br>',
                                    '<sup>','Random Values', '</sup>')))