This repository has been archived by the owner on Apr 1, 2023. It is now read-only.
forked from oliviaagore/PSY4960Spring2022Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGgplotPartTwo.Rmd
301 lines (243 loc) · 11.1 KB
/
GgplotPartTwo.Rmd
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
---
title: "Ggplot part 2"
author: "Amanda Mae Woodward"
date: "3/17/2022"
output: html_document
---
# Learning Outcomes
By the end of this class, students should be able to:
- Explain how to alter information in the legend
- Describe how to use facet wrap
- Explain how to export graphs
- Identify Code to create a shiny app
### Learning Outcome 1: Explain how to alter information in the legend
It can also be helpful to understand how to modify your legend:
+ theme(legend.position="none") will remove the legend. You can also choose to move the legend to the top or bottom of the graph
Let's try this on a graph from the diamonds dataset:
Create a subset of the diamonds dataset:
```{r}
library(ggplot2)
data(diamonds)
```
Create a graph including information about price and carat. Include cut in some way:
```{r}
ggplot(diamonds, aes(carat, price, color=as.factor(cut)))+ geom_point()+ theme_classic()+ scale_color_viridis(discrete= TRUE, option= "A")
```
Notice what the legend looks like. To remove it we can add:
theme(legend.position="none")
```{r}
ggplot(diamonds, aes(carat, price, color=as.factor(cut)))+ geom_point()+ theme_classic()+ scale_color_viridis(discrete= TRUE, option= "A")+ theme(legend.position= "none")
```
We can also change the location:
```{r}
ggplot(diamonds, aes(carat, price, color=as.factor(cut)))+ geom_point()+ theme_classic()+ scale_color_viridis(discrete= TRUE, option= "A")+ theme(legend.position= "bottom")
```
To Change the legend title, you can use a couple of different codes, depending on the type of data:
scale_color_discrete(name="Title") works for scatter plots filled in with a factor
scale_fill_discrete(name="Title) should work for a bar graph filled in by a factor
scale_color_continuous() and scale_fill_continuous should work for a numeric fill
```{r}
ggplot(diamonds, aes(carat, price, color=as.factor(cut)))+ geom_point()+ theme_classic()+ scale_color_viridis(discrete= TRUE, option= "A",name= "Cut of Diamond")+ theme(legend.position= "bottom")
```
### Practice:
1) make a graph of disp and hp from mtcars. Include miles per gallon as a third variable
```{r}
ggplot(mtcars, aes(disp, hp, color=as.factor(mpg)))+ geom_point()
```
2) Move the legend to the top of the graph
```{r}
ggplot(mtcars, aes(disp, hp, color=as.factor(mpg)))+ geom_point()+ theme_classic()+theme(legend.position="top")
```
3) Remove the legend from the graph
```{r}
ggplot(mtcars, aes(disp, hp, color=as.factor(mpg)))+ geom_point()+ theme_classic()+theme(legend.position="none")
```
4) Change the title of the legend
```{r}
ggplot(mtcars, aes(disp, hp, color=as.factor(mpg)))+ geom_point()+ theme_classic()+theme(legend.position="top")+scale_color_viridis(discrete=TRUE, option="A", name ="Miles per Gallon")
```
### Learning Outcome 2: Describe how to use facet wrap
Facet Wrap allows us to incorporate a third variable in another way. Specifically, it panels graphs so that we can make an individual graph for each level of a factor.
we need to make a graph and save it (we'll use carat and price)
```{r}
graph<- ggplot(diamonds, aes(carat, price))+ geom_point()
graph
```
then we'll use cut to create the facets
```{r}
graph+ facet_wrap(~cut)
```
```{r}
library(ggplot2)
ggplot(diamonds, aes(carat, price))+ geom_point()+ facet_wrap(~cut)
ggplot(mtcars, aes(mpg, hp, color=as.factor(cyl)))+ geom_point()+ facet_wrap(~gear)
```
### Practice:
1) create a facet wrap graph to generate a scatterplot of mpg and hp based on the number of cylinders a car has
```{r}
ggplot(mtcars, aes(mpg, hp)) + geom_point(color="skyblue")+facet_wrap(~as.factor(cyl))
#as continuous
ggplot(mtcars, aes(mpg, hp)) + geom_point()+facet_wrap(~cyl)
#variable approach
mpghp<- ggplot(mtcars, aes(mpg, hp))+ geom_point(color= "pink")+ theme_classic()
mpghp + facet_wrap(~cyl)
```
### Learning Outcome 3: Explain how to export graphs
to export graphs, I use the command ggsave()
Specifically, you can use the following arguments:
```{r}
ggsave()
ggsave("mtcars-mpgvshp.tiff",width=10, heigh=10, units="in", dpi= 300)
```
I don't usually specify a path in ggsave, but make sure my r code is in the directory I'd like it to be saved in. you can check your working directory by using this code
```{r}
ggsave("mtcars-mpgvshp.tiff",width=10, heigh=10, units="in", dpi= 300, path= "insert path here")
"path for saving files"
```
you can change your working directory using this code:
```{r}
getwd()
```
### Learning Outcome 4: Identify Code to create a shiny app
## Before we get started
Shiny apps are advanced. Even if we're focusing on "basics" the coding behind it is more advanced than what we covered last week. It's **ok** if you walk away from the lesson not knowing what I'm talking about.
The plan is to **show** you what you can build to as you program in R. There are tutorials that are ~18 hours to complete. We can't do that in one class. I've included links that I use when making shiny apps that you may want to try.
#### Identify Code to create a shiny app
shiny is a package in R that allows us to create interactive graphs. You can create dashboards and place interactive graphs online.
Today should be treated as an introduction. You can learn more here: https://shiny.rstudio.com/tutorial/
People make shiny apps in different ways, I'm going to use naming conventions and descriptions used by R Studio developers because it makes it easier to follow along.
But first, we need to load the shiny package.
```{r}
library(shiny)
```
Before we start coding, we need to talk about the different aspects of a shiny app:
**User Interface:** We're programming the part that someone would see in the plot
- If you place it on the internet, this would be the portion that others would see
**Server:** This is the background code to create what the user sees. It's what the computer runs in the background. (ie R code)
The **User Interface** creates the webpage, and the **server** tells R how to put the pieces together.
Then, **shinyApp** combines the information in the User interface and the Server. We'll start with an example below to get an idea of the structure.
Just like we started with ggplot, we'll start with a shell.
```{r}
ui <- fluidPage()
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
```
I am using ui to stand for the user interface. This is going to be what someone would see. Notice that the server is a function that we are designing, and we're giving it inputs and outputs. In this case, it is an empty function.
Whatever we put in the fluidpage() function above is going to be present in our shiny app.
```{r}
ui <- fluidPage("I LOVE PSY4960!")
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
```
You can see that whatever I write in fluid page, shows up in the app. When we want to add more to what other people will see, we need to specify different inputs and outputs.
In this section, we will talk about different inputs and outputs you can use.
**Creating a scale**
Making graphs is complex. We're going to start with making a scale input because it helps us understand how the input functions work.
All inputs follow similar structures, so you will be able to apply this general format to other options.
The function to make a scale is sliderInput() and takes the following inputs:
sliderInput(inputId, label, min, max, value)
Just looking at the input code (not in the shiny app), it will look something like this:
```{r}
sliderInput(inputId="number", label="Pick a number", value=13, min=1, max=100)
```
When we put it in the ui/server code we used to make the app:
```{r}
ui <- fluidPage(
sliderInput(inputId = "number",
label = "Pick a number",
value = 13, min = 1, max = 100),
plotOutput("hist")
)
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
```
This code lets a person using the Shiny app pick a number between 1 and 100. We can then use this to create an output that will change based on people's responses.
**Creating a graph**
In this example, we'll create a histogram that plots a random normal sample of size n (whatever the person picks).
Before we look at the shiny app code, I need to walk you through the code we'll use as an output.
first, we'll use rnorm. We can use this function to draw a random sample from a normal distribution (mean= 0, sd=1).
```{r}
rnorm(100)
```
We'll put this into a plot (which will let me show you a way to graph vectors not in a dataframe)
```{r}
ggplot(, aes(rnorm(1000)))+ geom_histogram(fill="darksalmon")+theme_classic()
```
```{r}
ui <- fluidPage(
sliderInput(inputId = "number",
label = "Pick a number",
value = 13, min = 1, max = 100),
plotOutput("hist")
)
server <- function(input, output) {
output$hist <- renderPlot({
ggplot(, aes(rnorm(input$number)))+ geom_histogram(fill="darksalmon")+theme_classic()
})
}
shinyApp(ui = ui, server = server)
```
#### Practice (Challenge)
1. Create a shiny app that allows people to select a number between 1 and 5000.
2. Add an output that creates a graph based on these numbers.
```{r}
ui <- fluidPage(
sliderInput(inputId = "number",
label = "Pick a number",
value = 13, min = 1, max = 5000),
plotOutput("hist")
)
server <- function(input, output) {
output$hist <- renderPlot({
ggplot(, aes(rnorm(input$number)))+ geom_histogram(fill="darkblue")+theme_classic()
})
}
shinyApp(ui = ui, server = server)
```
**Challenge:** Create a graph based on two numbers chosen by the user
### Using real data in a shiny app
For this graph, we're going to use built in R data and allow users to choose what they'd like to graph. To do this, we'll use a dropdown list as the input. (for other inputs: https://shiny.rstudio.com/images/shiny-cheatsheet.pdf)
Just like we did before, I'll show you what code we're adding to the ui side before we add it.
We're going to use the diamonds dataset for this practice
```{r}
data(diamonds)
```
**User Interface Set up**
The first part we'll set up is the ui. We'll be making a drop down list.
To make a dropdown list, we'll use the selectInputs function. It takes the following arguments:
selectInput(inputId, label (what other people see), choices(that people can choose from))
```{r}
ui<- fluidPage(
titlePanel("diamonds data"),
sidebarLayout(
sidebarPanel(
selectInput(inputId= "colorChoice", label="Select Diamond Color", choices= c("D"="D", "E"="E", "F"= "F", "G"="G", "H"="H", "I"="I", "J"="J"))),
mainPanel(
plotOutput("colorgraph")
)
)
)
server <- function(input, output) {
output$colorgraph <- renderPlot({
ggplot(diamonds[diamonds$color==input$colorChoice,], aes(carat))+ geom_histogram(fill= "lightseagreen",bins= 50)+theme_classic()
})
}
shinyApp(ui = ui, server = server)
```
```{r}
ui<- fluidPage(
titlePanel("diamonds data"),
sidebarLayout(
sidebarPanel(
selectInput(inputId= "colorChoice", label="Select Diamond Color", choices= c("D"="D", "E"="E", "F"= "F", "G"="G", "H"="H", "I"="I", "J"="J"))),
mainPanel(
plotOutput("colorgraph")
)
)
)
server <- function(input, output) {
output$colorgraph <- renderPlot({
ggplot(diamonds[diamonds$color==input$colorChoice,], aes(carat, price))+ geom_point(color= "lightseagreen")+theme_classic()
})
}
shinyApp(ui = ui, server = server)