Chapter 3 R HomeWork 1

3.1 Problem 1 : Histogram

  • 3.1 Answer 1

library(ggplot2)
ggplot(data = mpg, aes(x = hwy, fill = drv)) +
  geom_histogram(alpha = 0.5) + 
  theme_minimal() +
  labs(title = "Histogram", 
     subtitle = "Histogram of Highway Mile Per Gallon", 
     caption = "Source: mpg",
     x = "hwy", 
     y = "count",
     fill = "drv")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

3.2 Problem 2 : Histogram using facet_grid()

  • 3.2 Answer 2

library(ggplot2)
ggplot(mpg, aes(x = hwy, fill = drv)) +
  geom_histogram(alpha = 0.5) +
  theme_minimal() +
  facet_grid(rows = vars(drv))+
  labs(title = "Histogram using facet_grid()", 
       subtitle = "Histogram of Highway Mile Per Gallon", 
       caption = "Source: mpg",
       x = "hwy", 
       y = "count", 
       fill = "drv")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

3.3 Problem 3 : Scatterplot

  • 3.3 Answer 3

library(ggplot2)
options(scipen=999)
ggplot(midwest, aes(x = area, y = poptotal)) +   
  geom_point(aes(size = popdensity, color = state), alpha = 0.4) + 
  geom_smooth(se = FALSE) +
  xlim(c(0,0.1)) + ylim(c(0,500000)) +
  theme_classic() +
  labs(title = "ScatterPlot", 
       subtitle = "Area Vs Population",
       caption = "Source: midwest", 
       x = "Area", 
       y = "Population", 
       color = "state",
       size = "popdensity")
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

3.4 Problem 4 : Scatterplot

  • 3.4 Answer 4

library(datasets)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, shape = Species)) +
  geom_point(alpha = 0.5, size = 6) +
  labs(title = "Scatterplot", 
       subtitle = "Sepal.Length Vs Sepal.Width",
       caption = "Source: iris",
       x = "Sepal.Length", 
       y = "Sepal.Width", 
       color = "Species") +
  theme_minimal()

3.5 Problem 5 : Scatterplot

  • 3.5 Answer 5

library(gcookbook)
ggplot(heightweight, aes(x = heightIn, y = weightLb, color = sex )) +
  geom_point(alpha = 0.5, size = 3)+
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "ScatterPlot", 
       subtitle = "Weight Vs Height",
       caption = "Source: heightweight",
        x = "heightIn", 
       y = "weightLb", 
       color = "sex") +  
  theme_classic()
## `geom_smooth()` using formula 'y ~ x'

3.6 Problem 6 : Barplot

  • 3.6 Answer 6

library(ggplot2)
library(RColorBrewer)
ggplot(mpg, aes(x = manufacturer, fill = class)) +
  geom_bar(width = 0.5) +
  labs(title = "Barplot", 
       subtitle = "Manufacturer across Vehicle Classes",
       x = "manufacturer",
       y = "count", 
       color = "class") +
  scale_fill_brewer(palette = "Spectral") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 65, vjust = 0.5))