Carregar pacotes ggplot2 e MASS e carregar dataframe Cars93.
library(ggplot2)
library(MASS)
View(Cars93)
Um gráfico começa com ggplot ( ), que recebe dois argumentos. Primeiro é a fonte de dados, em seguida precisamos mapear os componentes do gráfico, e a função para isso é o aes. A função aesassociando o Priceao eixo x. No GGPLOT é chamado mapeamento estético.
Essa linha de código faz uma grade de fundo cinza e Priceno eixo x.
ggplot(Cars93, aes(x=Price))
Para desenhar um histograma, adicionamos a função geom_histograma ().
ggplot(Cars93, aes(x=Price)) + geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
E adicionamos argumentos adicionais:
ggplot(Cars93, aes(x=Price))+ geom_histogram(binwidth = 5, color="black", fill="white") + labs (x = "Price (x $1000)", y="Frequency", title= "Price of 93 Models of 1993 Cars")
Argumento binwidth - Especifica a largura de cada bin (barra), labs - modifica os rótulos dos eixos e title fornece um título para o gráfico.
Usando o banco de dados do R mpg
Histograma em variáveis contínuas
library(ggplot2)
theme_set(theme_classic())
# Histogram on a Continuous (Numeric) Variable
g <- ggplot(mpg, aes(displ)) + scale_fill_brewer(palette = "Spectral")
g + geom_histogram(aes(fill=class),
binwidth = .1,
col="black",
size=.1) + # change binwidth
labs(title="Histogram with Auto Binning",
subtitle="Engine Displacement across Vehicle Classes")
g + geom_histogram(aes(fill=class),
bins=5,
col="black",
size=.1) + # change number of bins
labs(title="Histogram with Fixed Bins",
subtitle="Engine Displacement across Vehicle Classes")
Histograma em variáveis categóricas
library(ggplot2)
theme_set(theme_classic())
# Histogram on a Categorical variable
g <- ggplot(mpg, aes(manufacturer))
g + geom_bar(aes(fill=class), width = 0.5) +
theme(axis.text.x = element_text(angle=65, vjust=0.6)) +
labs(title="Histogram on Categorical Variable",
subtitle="Manufacturer across Vehicle Classes")
Referências
Schmuller, Joseph. Análise Estatística com R - Para leigos - Tradução da 2a edição. Alta Books Editora. 2019.
Oliveira, Paulo; Guerra, Saulo; McDonnell, Robert. Ciência de Dados com R. Introdução.Editora IBPAD. Brasília. 2018. Disponível em: {https://cdr.ibpad.com.br/cdr-intro.pdf}