The objectives of this problem set is to gain experience working with the ggplot2 package for data visualization. To do this I have provided a series of graphics, all created using the ggplot2 package. Your objective for this assignment will be write the code necessary to exactly recreate the provided graphics.
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.
library(ggplot2)
library(reshape2)
# counts (or sums of weights)
g <- ggplot(mpg, aes(class))
g + 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
p <- ggplot(mpg, aes( manufacturer,hwy))
p + geom_boxplot()+ theme_classic() + coord_flip() + labs(y = "Highway Fuel Efficiency (mile/gallon)", x = "Vehicle Manufacturer")
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.
#install.packages("ggthemes")
library(ggthemes)
#gg-plot for diamonds dataset
g <- ggplot(diamonds, aes(x = price, color = cut, fill = cut))
#Density of diamond price
g + geom_density(aes(fill=factor(cut)), alpha=0.2, size =0.8)+ 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.
ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point() + geom_smooth(method = lm) + theme_minimal() + theme(panel.grid.major = element_line(size = 1), panel.grid.minor = element_line(size = 0.7)) +labs(title = "Relationship between Petal and Sepal Length",x = "Iris Sepal Length", y = "Iris Petal Length")
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.
ggplot(iris,aes(Sepal.Length,Petal.Length,color = Species)) + geom_point() + geom_smooth(method = lm, se = FALSE) + theme_pander() + theme(text = element_text(family = "serif"), axis.ticks = element_line(color = "black", size = 0.7),legend.position = "bottom", legend.title = element_text(face = "plain"), plot.title = element_text(size = 14, face = "plain")) + labs(title = "Relationship between Petal and Sepal Length", subtitle = "Species level comparison", x = "Iris Sepal Length", y = "Iris Petal Length")