Graphs
Página com arquivo do script em RMarkdown
# 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 for more information
penguins <- penguins_raw # ?penguins_raw for more information penguins_raw
Bar Graphs
(N) Basic
%>% # Dataset
(penguins ggplot(aes(sex)) + # Coluna de interesse
geom_bar()) # Formato de barras
(N) Complete
%>% drop_na(sex) %>% # Remove os NAs
(penguins 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
%>% drop_na(sex) %>% # Remove os NAs
(penguins 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
%>% drop_na(sex) %>%
(penguins ggplot(aes(sex)) +
geom_bar(aes(y = (..count..)/sum(..count..))))
(%) Complete
%>% drop_na(sex) %>% # Remove os NAs
(penguins 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
%>% drop_na(sex) %>% # Remove os NAs
(penguins 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
%>% drop_na(flipper_length_mm) %>%
(penguins ggplot(aes(x = flipper_length_mm)) +
geom_histogram())
Complete
%>% drop_na(flipper_length_mm) %>% # remover NAs
(penguins 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
%>% drop_na(flipper_length_mm) %>% # remover NAs
(penguins 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
%>% drop_na(flipper_length_mm) %>%
(penguins 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
<- ddply(penguins, "species", summarise, grp.mean=mean(flipper_length_mm, na.rm=TRUE))
mean %>% drop_na(flipper_length_mm) %>%
(penguins 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
<- ddply(penguins, "species", summarise, grp.mean=mean(flipper_length_mm, na.rm=TRUE))
mean %>% drop_na(flipper_length_mm) %>%
(penguins 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
::summarise(N = n()) %>% # N = contagem das espécies
dplyrggplot(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 ::mutate(n_all = n()) %>% # n_all = soma de todas contagens únicas
dplyrgroup_by(species) %>% # separação nos grupos de espécies
::summarise(N = n() / unique(n_all)) %>% # N = contagem das espécies / total de contagens únicas
dplyrggplot(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
%>% drop_na(flipper_length_mm) %>%
penguins ggplot(aes(x = species, y = flipper_length_mm))+
geom_boxplot()
Complete
%>% drop_na(flipper_length_mm) %>%
(penguins 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
%>% drop_na(flipper_length_mm) %>%
penguins ggplot(aes(x=species, y=flipper_length_mm))+
::stat_halfeye(aes(fill = species), alpha = 0.4, show.legend = FALSE, adjust = .5, width = .6, .width = 0, justification = -.3) +
ggdistgeom_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
%>% drop_na(flipper_length_mm) %>%
(penguins ggplot(aes(flipper_length_mm, bill_length_mm))+
geom_point())
Complete
%>% drop_na(flipper_length_mm, bill_length_mm) %>%
(penguins 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
%>% drop_na(flipper_length_mm, bill_length_mm) %>%
(penguins 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
<- 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_pengu
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
<- rcorr(as.matrix(mtcars), type = c("spearman"))
matrix $P[is.na(matrix$P)] <- 0
matrix
::ggcorrplot(matrix$r, #a matriz a ser visualizada
ggcorrplot#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
<- data.frame(scale(mtcars)) # normalizar valores
mtcars_scale $model <- rownames(mtcars_scale) # cria coluna com "row.names"
mtcars_scale<- melt(mtcars_scale, id.vars = "model") # tranpõe toda tabela mantendo como fixo o id.vars
mtcars_melt
%>%
(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)
<- read_state(code_state="all", year = 2020, showProgress = FALSE)#pegando mapa com todos os estados do Brasil
br
#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
$value <- runif(27, 1, 99) # não tenho dataset, então só gerei uns números aleatórios
br
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>')))