from today.com
In this practical you’ll practice plotting data with the amazing ggplot2
package. By the end of this practical you will know how to:
BernRBootcamp
R project. It should already have the folders 1_Data
and 2_Code
. Make sure that the data files listed in the Datasets
section above are in your 1_Data
folder.# Done!
Open a new R script. At the top of the script, using comments, write your name and the date. Save it as a new file called plotting_practicalI.R
in the 2_Code
folder.
Using library()
load the set of packages for this practical listed in the Functions section above.
## NAME
## DATE
## Plotting Practical
library(XX)
library(XX)
#...
library(tidyverse)
mcondalds.csv
data set, which contains nutrition information about items from McDonalds. Using read_csv()
, load the data into R and store it as a new object called mcdonalds
.mcdonalds <- read_csv("1_Data/mcdonalds.csv")
mcdonalds
# A tibble: 260 x 24
Category Item `Serving Size` Calories `Calories from … `Total Fat`
<chr> <chr> <chr> <dbl> <dbl> <dbl>
1 Breakfa… Egg … 4.8 oz (136 g) 300 120 13
2 Breakfa… Egg … 4.8 oz (135 g) 250 70 8
3 Breakfa… Saus… 3.9 oz (111 g) 370 200 23
4 Breakfa… Saus… 5.7 oz (161 g) 450 250 28
5 Breakfa… Saus… 5.7 oz (161 g) 400 210 23
6 Breakfa… Stea… 6.5 oz (185 g) 430 210 23
7 Breakfa… Baco… 5.3 oz (150 g) 460 230 26
8 Breakfa… Baco… 5.8 oz (164 g) 520 270 30
9 Breakfa… Baco… 5.4 oz (153 g) 410 180 20
10 Breakfa… Baco… 5.9 oz (167 g) 470 220 25
# … with 250 more rows, and 18 more variables: `Total Fat (% Daily
# Value)` <dbl>, `Saturated Fat` <dbl>, `Saturated Fat (% Daily
# Value)` <dbl>, `Trans Fat` <dbl>, Cholesterol <dbl>, `Cholesterol (% Daily
# Value)` <dbl>, Sodium <dbl>, `Sodium (% Daily Value)` <dbl>,
# Carbohydrates <dbl>, `Carbohydrates (% Daily Value)` <dbl>, `Dietary
# Fiber` <dbl>, `Dietary Fiber (% Daily Value)` <dbl>, Sugars <dbl>,
# Protein <dbl>, `Vitamin A (% Daily Value)` <dbl>, `Vitamin C (% Daily
# Value)` <dbl>, `Calcium (% Daily Value)` <dbl>, `Iron (% Daily
# Value)` <dbl>
mcdonalds
data frame has many column names with spaces and ‘bad’ characters like parentheses. Run the following code to fix that!# Clean up the names of mcdonalds
mcdonalds <- mcdonalds %>%
select(-contains("% Daily Value")) %>% # Remove all '% Daily Value' columns
rename_all(.funs = ~ gsub(" ", "", .)) # no more spaces!
# Clean up the names of mcdonalds
mcdonalds <- mcdonalds %>%
select(-contains("% Daily Value")) %>% # Remove all '% Daily Value' columns
rename_all(.funs = ~ gsub(" ", "", .)) # no more spaces!
mcdonalds
# A tibble: 260 x 14
Category Item ServingSize Calories CaloriesfromFat TotalFat SaturatedFat
<chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Breakfa… Egg … 4.8 oz (13… 300 120 13 5
2 Breakfa… Egg … 4.8 oz (13… 250 70 8 3
3 Breakfa… Saus… 3.9 oz (11… 370 200 23 8
4 Breakfa… Saus… 5.7 oz (16… 450 250 28 10
5 Breakfa… Saus… 5.7 oz (16… 400 210 23 8
6 Breakfa… Stea… 6.5 oz (18… 430 210 23 9
7 Breakfa… Baco… 5.3 oz (15… 460 230 26 13
8 Breakfa… Baco… 5.8 oz (16… 520 270 30 14
9 Breakfa… Baco… 5.4 oz (15… 410 180 20 11
10 Breakfa… Baco… 5.9 oz (16… 470 220 25 12
# … with 250 more rows, and 7 more variables: TransFat <dbl>,
# Cholesterol <dbl>, Sodium <dbl>, Carbohydrates <dbl>, DietaryFiber <dbl>,
# Sugars <dbl>, Protein <dbl>
In this section, you’ll build the following plot step by step.
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point() +
geom_smooth(col = "black") +
labs(title = "McDonalds Nutrition",
subtitle = "Each point is a menu item",
caption = "Source: Kaggle.com") +
xlim(0, 1250) +
theme_minimal()
ggplot()
, create the following blank plot using the data
and mapping
arguments (but no geom). Use Calories
for the x aesthetic and SaturatedFat
for the y aestheticggplot(data = mcdonalds,
mapping = aes(x = XX, y = XX))
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat))
geom_point()
, add points to the plotggplot(data = mcdonalds,
mapping = aes(x = XX, y = XX)) +
geom_point()
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat)) +
geom_point()
color
aesthetic mapping, color the points by their Category
.ggplot(mcdonalds, aes(x = XX, y = XX, col = XX)) +
geom_point()
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point()
geom_smooth()
.ggplot(mcdonalds, aes(x = XX, y = XX, col = XX)) +
geom_point() +
geom_smooth()
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point() +
geom_smooth()
"black"
. When you do, you should then only see one line.ggplot(mcdonalds, aes(x = XX, y = XX, col = XX)) +
geom_point() +
geom_smooth(col = "XX")
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point() +
geom_smooth(col = "black")
labs()
function.ggplot(mcdonalds, aes(x = XX, y = XX, col = XX)) +
geom_point() +
geom_smooth(col = "XX") +
labs(title = "XX",
subtitle = "XX",
caption = "XX")
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point() +
geom_smooth(col = "black") +
labs(title = "McDonalds Nutrition",
subtitle = "Each point is a menu item",
caption = "Source: Kaggle.com")
0
and 1250
using xlim()
.ggplot(mcdonalds, aes(x = XX, y = XX, col = XX)) +
geom_point() +
geom_smooth(col = "XX") +
labs(title = "XX",
subtitle = "XX",
caption = "XX") +
xlim(XX, XX)
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point() +
geom_smooth(col = "black") +
labs(title = "McDonalds Nutrition",
subtitle = "Each point is a menu item",
caption = "Source: Kaggle.com") +
xlim(0, 1250)
theme_minimal()
. You should now have the final plot!ggplot(mcdonalds, aes(x = XX, y = XX, col = XX)) +
geom_point() +
geom_smooth(col = "XX") +
labs(title = "XX",
subtitle = "XX",
caption = "XX")+
xlim(XX, XX) +
theme_minimal()
ggplot(mcdonalds, aes(x = Calories, y = SaturatedFat, col = Category)) +
geom_point() +
geom_smooth(col = "black") +
labs(title = "McDonalds Nutrition",
subtitle = "Each point is a menu item",
caption = "Source: Kaggle.com") +
xlim(0, 1250) +
theme_minimal()
ggplot(data = mcdonalds, aes(x = XX, y = XX, fill = XX)) +
geom_violin() +
guides(fill = FALSE) +
labs(title = "XX",
subtitle = "XX")
ggplot(data = mcdonalds, aes(x = Category, y = Calories, fill = Category)) +
geom_violin() +
guides(fill = FALSE) +
labs(title = "McDonalds",
subtitle = "Calorie distribution by menu category")
+ stat_summary(fun.y = "mean", geom = "point", col = "white", size = 4)
to include points showing the mean of each distributionggplot(data = mcdonalds, aes(x = Category, y = Calories, fill = Category)) +
geom_violin() +
guides(fill = FALSE) +
stat_summary(fun.y = "mean", geom = "point", col = "white", size = 4) +
labs(title = "McDonalds",
subtitle = "Calorie distribution by menu category")
+ geom_jitter(width = .1, alpha = .5)
to your plot, what do you see?ggplot(data = mcdonalds, aes(x = Category, y = Calories, fill = Category)) +
geom_violin() +
geom_jitter(width = .1, alpha = .5) +
guides(fill = FALSE) +
stat_summary(fun.y = "mean", geom = "point", col = "white", size = 4) +
labs(title = "McDonalds",
subtitle = "Calorie distribution by menu category")
stat_summary()
from "mean"
to "median"
.stat_summary()
to something much bigger (or smaller).width
argument in geom_jitter()
to width = 0
.geom_violin()
, try geom_boxplot()
.fill = Category
aesthetic entirely.ggplot(XX, aes(x = XX, y = X)) +
stat_summary(geom = "bar",
fun.y = "mean") +
labs(title = "XX",
subtitle = "XX")
ggplot(mcdonalds, aes(x = Category, y = Calories)) +
stat_summary(geom = "bar",
fun.y = "mean") +
labs(title = "Calories by McDonalds menu category",
subtitle = "Bars represent means")
"mean"
, show the "median"
.geom_point()
, geom_count()
or geom_jitter()
.Let’s create the following plot with additional point labels using geom_text()
:
ggplot(mcdonalds, aes(x = Sugars,
y = Calories,
col = Category,
label = Item)) +
geom_point() +
geom_text(data = mcdonalds %>%
filter(Calories > 1100),
col = "black",
check_overlap = TRUE,
hjust = "left") +
xlim(0, 150) +
ylim(0, 2000) +
theme_minimal() +
labs(title = "Adding labels to a plot with geom_text()")
ggplot(mcdonalds, aes(x = XX,
y = XX,
col = XX)) +
geom_point() +
xlim(XX, XX) +
ylim(XX, XX) +
theme_minimal() +
labs(title = "XX")
Try adding labels to the plot indicating which item each point represents by adding + geom_text()
.
Where are the labels? Ah, we didn’t tell ggplot
which column in the data represents the item descriptions. Fix this by specifying the label
aesthetic in your first call to the aes()
function. That is, include label = Item
underneath the line col = XX
. Now you should see lots of labels!
Customize your geom_text()
by including the arguments: geom_text(col = "black", check_overlap = TRUE, hjust = "left")
.
Using the data
argument in geom_text()
, specify that the labels should only apply to items over 1100 calories (hint: geom_text(data = mcdonalds %>% filter(XX > XX))
)
Play around!
size
aesthetic.theme_excel()
included in the ggthemes
package.# ggplot2 -----------------------
library(tidyverse) # Load tidyverse (contains ggplot2!)
mpg # Look at the mpg data
# Just a blank space without any aesthetic mappings
ggplot(data = mpg)
# Now add a mapping where engine displacement (displ) and highway miles per gallon (hwy) are
# mapped to the x and y aesthetics
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy)) # Map displ to x-axis and hwy to y-axis
# Add points with geom_point()
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy)) +
geom_point()
# Add points with geom_count()
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy)) +
geom_count()
# Again, but with some additional arguments
# Also using a new theme temporarily
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy)) +
geom_point(col = "red", # Red points
size = 3, # Larger size
alpha = .5, # Transparent points
position = "jitter") + # Jitter the points
scale_x_continuous(limits = c(1, 15)) + # Axis limits
scale_y_continuous(limits = c(0, 50)) +
theme_minimal()
# Assign class to the color aesthetic and add labels with labs()
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy, col = class)) + # Change color based on class column
geom_point(size = 3, position = 'jitter') +
labs(x = "Engine Displacement in Liters",
y = "Highway miles per gallon",
title = "MPG data",
subtitle = "Cars with higher engine displacement tend to have lower highway mpg",
caption = "Source: mpg data in ggplot2")
# Add a regression line for each class
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy, color = class)) +
geom_point(size = 3, alpha = .9) +
geom_smooth(method = "lm")
# Add a regression line for all classes
ggplot(data = mpg,
mapping = aes(x = displ, y = hwy, color = class)) +
geom_point(size = 3, alpha = .9) +
geom_smooth(col = "blue", method = "lm")
# Another fancier example
ggplot(data = mpg,
mapping = aes(x = cty, y = hwy)) +
geom_count(aes(color = manufacturer)) + # Add count geom (see ?geom_count)
geom_smooth() + # smoothed line without confidence interval
geom_text(data = filter(mpg, cty > 25),
aes(x = cty,y = hwy,
label = rownames(filter(mpg, cty > 25))),
position = position_nudge(y = -1),
check_overlap = TRUE,
size = 5) +
labs(x = "City miles per gallon",
y = "Highway miles per gallon",
title = "City and Highway miles per gallon",
subtitle = "Numbers indicate cars with highway mpg > 25",
caption = "Source: mpg data in ggplot2",
color = "Manufacturer",
size = "Counts")
File | Rows | Columns |
---|---|---|
mcdonalds.csv | 260 | 24 |
Package | Installation |
---|---|
tidyverse |
install.packages("tidyverse") |
ggthemes |
install.packages("ggthemes") |
The main ggplot2
webpage at http://ggplot2.tidyverse.org/ has great tutorials and examples.
Check out Selva Prabhakaran’s website for a nice gallery of ggplot2 graphics http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html
ggplot2
is also great for making maps. For examples, check out Eric Anderson’s page at http://eriqande.github.io/rep-res-web/lectures/making-maps-with-R.html
from R Studio