forked from BaruqueRodrigues/Curso-de-R
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaula_5_o_basico_da_gramatica_dos_graficos.R
322 lines (233 loc) · 8.4 KB
/
aula_5_o_basico_da_gramatica_dos_graficos.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
### Data Visualization - Parte 1 ###
# Pacotes Utilizados
library(ggplot2) # Pacote gráfico
library(nycflights13) # Dados Utilizados
library(dplyr) # Manipula??o dos Dados
# O que é a DataVis e por que ela é importante?
flights
# Existem Multiplas formas de visualizar dados
flights
glimpse(flights)
View(flights)
flights$arr_time
flights$arr_delay
table(flights$arr_time)
table(flights$arr_delay)
arr_time
arr_delay
# Apresentando a gr?matica dos gráficos
# grammar of graphs
#Um grafico estatistico é um mapeamento de variáveis de dados para atributos
# estéticos de objetos geométricos.
ggplot(data = a, # dataset que contem as variáveis de interesse
mapping = aes(x = arr_time) # atributos estéticos posição de X e Y, cor, forma e tamanho.
)+ # operador que adiciona camadas aos gráficos
geom_histogram() # geom_ o objeto geométrico em questão
## The Big Five
# Os 5 tipos de gráfico que todo analista deve conhecer
# Gráficos univariados
# histograms - histogramas;
# boxplots - gráficos de caixa;
# barplots - gráficos de barra;
#Gráficos Bivariados
# scatterplots - gráficos de dispersão;
# linegraphs - gráficos de linha;
## Histogramas
# Fazendo um Histograma
ggplot(data = weather,
aes(x = temp)) +
geom_histogram()
# Alterando a cor de um geom
ggplot(data = weather,
aes(x = temp)) +
geom_histogram(color = "white")
# O que alterou desse histograma para o primeiro?
# Para alterar a parte interna de um geom utilizamos o argumento fill
ggplot(data = weather,
aes(x = temp)) +
geom_histogram(color = "white", fill = "steelblue")
# Utilizamos o argumento bins para alterar o número de colunas do histograma
ggplot(data = weather,aes(x = temp)) +
geom_histogram(bins = 40, color = "white", fill = "steelblue")
# Utilizamos a função binwidth para alterar o tamanho da coluna
ggplot(data = weather,aes(x = temp)) +
geom_histogram(binwidth = 10, color = "white", fill = "steelblue")
# Utilizamos o layer facets para criar paineis
ggplot(data = weather,
aes(x = temp)) +
geom_histogram(binwidth = 5, color = "white", fill = "red") +
facet_wrap(~ month)
# Podemos alterar o tamanho do painel a ser plotado
ggplot(data = weather,
aes(x = temp)) +
geom_histogram(binwidth = 5, color = "white", fill = "red") +
facet_wrap(~ month, nrow = 4)
ggplot(data = weather,
aes(x = temp)) +
geom_histogram(binwidth = 5, color = "white", fill = "red") +
facet_wrap(~ month, nrow = 2, ncol = 6 )
## Boxplots
# Vendo a distribuição de uma vari?vel
ggplot(data = weather,
aes(y = temp)) +
geom_boxplot()
# Vendo a distribuição de multiplas vari?veis
ggplot(data = weather,
aes(x = month, y = temp)) +
geom_boxplot()
# Qual o erro?
ggplot(data = weather,
aes(x = factor(month), y = temp)) +
geom_boxplot()
## Barplots
# Simulando alguns dados
frutas <- tibble(
fruta = c("maçã", "maçã", "laranja", "maçã", "laranja"))
frutas_contadas <- tibble(
frutas = c("maçã", "laranja"),
numero = c(3, 2))
# Podemos Usar o geom_bar
ggplot(data = frutas,
aes(x = fruta)) +
geom_bar()
# Como também o geom_col
ggplot(data = frutas_contadas,
aes(x = frutas, y = numero)) +
geom_col()
# Qual a diferença entre os 2?
# geom_bar é ótimo para dados n?o contados no dataframe
# geom_col é ótimo para valores contados no dataframe
# Fazendo gráficos de proporções
# Usando o argumento fill
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar()
# Usando o argumento color
ggplot(data = a,
aes(x = carrier, color = origin)) +
geom_bar()
# Fazendo gráficos de barras agrupados fazendo uso do argumento position
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")
# Mantendo a proporção nas barras
ggplot(data = flights,
aes(x = carrier, fill = origin)) +
geom_bar(position = position_dodge(preserve = "single"))
## Scatterplot
#filtrando os dados do alaska
alaska <- flights %>%
filter(carrier == "AS")
# executando o gráfico
ggplot(data = alaska,
aes(x = dep_delay, y = arr_delay)) +
geom_point()
## O que fazer se os pontos se sobescreverem?
# Opção 1 alterando a transparência com a função alpha(), dentro do geom.
ggplot(data = alaska,
aes(x = dep_delay, y = arr_delay)) +
geom_point(alpha = .2)
# Opção 2 usando um geom que cause um "tremor"
ggplot(data = alaska,
aes(x = dep_delay, y = arr_delay)) +
geom_jitter()
# Opção 3 juntando tudo
ggplot(data = alaska,
aes(x = dep_delay, y = arr_delay)) +
geom_jitter(alpha = .2)
## Lineplot
# Pegando uma série temporal
clima_jan<- weather %>%
filter(origin == "EWR" & month == 1 & day <= 31)
ggplot(data = clima_jan,
aes(x = time_hour, y = temp)) +
geom_line()
## Alterando a Estrutura do gráfico
# Alterando os nomes dos eixos dos gráficos
# Fazemos uso da função labs()
ggplot(data = clima_jan,
aes(x = time_hour, y = temp)) +
geom_line()+
labs(title = "Titulo do gráfico",
subtitle = "Subtítulo do gráfico",
x = "título do Eixo X",
y = "título do Eixo Y",
caption = "Legenda do gráfico")
# Alterando o nome da legenda dos valores
# fazemos uso da função guides()
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))
# Alterando a posição da legenda
# Fazemos uso da função theme()
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme(legend.position = "bottom")
# Para alterar qualquer elemento do gráfico podemos usar a função theme
# centralizando o título
ggplot(data = clima_jan,
aes(x = time_hour, y = temp)) +
geom_line()+
labs(title = "Titulo do gráfico",
subtitle = "Subtítulo do gráfico",
x = "título do Eixo X",
y = "título do Eixo Y",
caption = "Legenda do gráfico")+
theme(plot.title = element_text(hjust = .5),
plot.subtitle = element_text(hjust = .5),
plot.caption = element_text(hjust =0))
# mudando a cor do fundo do gráfico, por exemplo
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme(legend.position = "bottom",
panel.background = element_rect(fill = "lightblue")
)
# mudando a cor do painel
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme(legend.position = "bottom",
panel.background = element_rect(fill = "lightblue", color = "red", size = 5)
)
# mudando o tipo de linha do painel
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme(legend.position = "bottom",
panel.background = element_rect(fill = "lightblue", color = "red",linetype = "dashed")
)
# alterando a cor painel
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme(legend.position = "bottom",
panel.background = element_rect(fill = "lightblue", color = "red",linetype = "dashed"),
plot.background = element_rect(fill = "green")
)
# alterando a posição dos valores do eixo x
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme(legend.position = "bottom",
panel.background = element_rect(fill = "lightblue", color = "red",linetype = "dashed"),
plot.background = element_rect(fill = "green"),
axis.text.x = element_text(angle = 90)
)
# também podemos usar temas pré definidos
ggplot(data = a,
aes(x = carrier, fill = origin)) +
geom_bar(position = "dodge")+
guides(fill = guide_legend("título da Legenda"))+
theme_light()+
theme(legend.position = "bottom")
# por fim, podemos usar o themeset pra definir o theme de todos os nossos gráficos.
theme_set()