mpglibrary(tidyverse)
library(ggplot2)
library(ggthemes)
glimpse(mpg)
## Rows: 234
## Columns: 11
## $ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi", "…
## $ model <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro", "…
## $ displ <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0, 2.…
## $ year <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, 200…
## $ cyl <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, …
## $ trans <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "auto…
## $ drv <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "4", "4…
## $ cty <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17, 1…
## $ hwy <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25, 2…
## $ fl <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p…
## $ class <chr> "compact", "compact", "compact", "compact", "compact", "c…
| Column | Meaning |
|---|---|
| manufacturer | manufacturer name |
| model | model name |
| displ | engine displacement, in liters |
| year | year of manufacture |
| cyl | number of cylinders |
| trans | type of transmission |
| drv | the type of drive train, where f = front-wheel drive, r = rear wheel drive, 4 = 4wd |
| cty | city miles per gallon |
| hwy | highway miles per gallon |
| fl | fuel type |
| class | type of car |
ggplot(mpg, aes(cty)) +
geom_histogram(binwidth = 5)
bar <- mpg %>%
count(manufacturer) %>%
ggplot(aes(x = reorder(manufacturer, n), y = n, fill = manufacturer))
bar + geom_bar(stat = 'identity') +
coord_flip() +
labs(title = "Manufacturer vs. Number of cars",
x = "Manufacturer",
y = "Number of cars",
caption = "data set: mpg")
scatter1 <- ggplot(mpg, mapping = aes(x = displ, y = hwy, color = class))
scatter1 + geom_point(alpha = 0.8) +
theme_light() +
geom_smooth(method = lm, color = "red") +
labs(title = "engine displacement(liters) VS.highway miles per gallon",
x = "engine displacement(liters)",
y = "highway miles per gallon",
caption = "data set: mpg")
toyota <- mpg %>%
filter(manufacturer == "toyota")
honda <- mpg %>%
filter(manufacturer == "honda")
scatter2 <- ggplot() +
geom_point(data = toyota, aes(cty, hwy), color = "blue") +
geom_point(data = honda, aes(cty, hwy), color = "red") +
theme_minimal() +
labs(title = "city miles/gallon VS. highway miles/gallon",
x = "city miles/gallon",
y = "highway miles/gallon",
caption = "data set: mpg")
scatter2
ggplot(mpg, aes(displ, hwy, color = cyl)) +
geom_point() +
geom_smooth(method = lm, color = "red") +
facet_wrap(~year, ncol = 2) +
labs(title = "engine displacement VS. highway miles/gallon by years",
x = "engine displacement (liters)",
y = "highway (miles per gallon)",
caption = "data set: mpg")