The objectives of this problem set is to gain experience working with the ggplot2 package for data visualization.
# code for loading the neccessary packages and reading the data file
library(datasets) ## Load the base R datasets
library(ggplot2) ## Load the ggplot2 package for making the plots
library(ggthemes) ## Load ggthemes package to for extra themes
This graphic is a traditional stacked bar chart. This graphic works on the mpg dataset, which is built into the ggplot2 library. This means that you can access it simply by ggplot(mpg, ….). There is one modification above default in this graphic, I renamed the legend for more clarity.
# Code for bar plot for class
ggplot(mpg, aes(class)) +
geom_bar(aes(fill = trans)) +
scale_fill_discrete(name = "Transmission")
This boxplot is also built using the mpg dataset. Notice the changes in axis labels, and an altered theme_XXXX
#code for BoxPlot for Highway fuel efficiency for the car models
ggplot(mpg, aes(manufacturer, hwy)) +
geom_boxplot() +
theme_classic() +
labs(x = "Vehicle Manufacturer", y = "Highway Fuel efficiency (mile/gallon)") +
coord_flip()
This graphic is built with another dataset diamonds a dataset also built into the ggplot2 package. For this one I used an additional package called library(ggthemes) check it out to reproduce this view.
# code for Diamond price density plot
ggplot(diamonds, aes(price, fill = cut, colour = cut)) +
geom_density(alpha = 0.1, size = 0.4) +
labs(title = "Diamond Price Density", x = "Diamond Price (USD)", y = "Density") +
theme_economist()
For this plot we are changing vis idioms to a scatter plot framework. Additionally, I am using ggplot2 package to fit a linear model to the data all within the plot framework. Three are edited labels and theme modifications as well.
#code for Petal and Sepal Length Scatter plot
ggplot(iris, aes(Sepal.Length, Petal.Length)) +
geom_point() +
geom_smooth(method = lm) +
labs(title = "Relationship between Petal and Sepal Length",
x = "Iris Sepal Length", y = "Iris Petal Length") +
theme_minimal() +
theme(panel.grid.major = element_line(size = 1), panel.grid.minor = element_line(size = 0.6))
Finally, in this vis I extend on the last example, by plotting the same data but using an additional channel to communicate species level differences. Again I fit a linear model to the data but this time one for each species, and add additional theme and labeling modicitations.
# Code for Vis 5
ggplot(iris, aes(Sepal.Length, Petal.Length, colour = Species)) +
geom_point() +
geom_smooth(se = FALSE, method = lm) +
theme(panel.background = element_blank()) +
theme(text = element_text(family = "serif"), axis.ticks = element_line(color = "black"),
legend.position = "bottom") +
labs(title = "Relationship between Petal and Sepal Length",
subtitle = "Species Level Comparison",
x = "Iris Sepal Length", y = "Iris Petal Length")