Skip to content

Lesson 6 Exercise Questions: ggplot2

Putting what we have learned to the test:
The following questions synthesize several of the skills you have learned thus far. It may not be immediately apparent how you would go about answering these questions. Remember, the R community is expansive, and there are a number of ways to get help including but not limited to google search. These questions have multiple solutions, but you should try to stick to the tools you have learned to use thus far.

Your mission is to make a publishable figure.

We will use the iris data set for this.

Start by plotting Petal.Length on the x-axis and Petal.Width on the y-axis.

Solution

library(ggplot2)
ggplot(iris)+
  geom_point(aes(Petal.Length,Petal.Width,color=Species))

Fix the axes so that the dimensions on the x-axis and the y-axis are equal. Both axes should start at 0. Label the axis breaks every 0.5 units on the y-axis and every 1.0 units on the x-axis.

Solution

ggplot(iris)+
  geom_point(aes(Petal.Length,Petal.Width,color=Species))+
  coord_fixed(ratio=1,ylim=c(0,2.75),xlim=c(0,7)) +
  scale_y_continuous(breaks=c(0,0.5,1,1.5,2,2.5)) +
  scale_x_continuous(breaks=c(0,1,2,3,4,5,6,7))

Change to color of the points by species to be color blind friendly, and change the legend title to "Iris Species". Label the x and y axis to eliminate the variable names and add unit information.

Solution

#multiple ways to find color blind friendly palettes. 
#using color brewer scales 
RColorBrewer::display.brewer.all(colorblindFriendly=TRUE)

ggplot(iris)+
  geom_point(aes(Petal.Length,Petal.Width,color=Species))+
  coord_fixed(ratio=1,ylim=c(0,2.75),xlim=c(0,7)) +
  scale_y_continuous(breaks=c(0,0.5,1,1.5,2,2.5)) +
  scale_x_continuous(breaks=c(0,1,2,3,4,5,6,7)) +
  scale_color_brewer(palette = "Dark2",name="Iris Species") +
  labs(x="Petal Length (cm)", y= "Petal Width (cm)")

Play with the theme to make this a bit nicer. Change font style to "Times". Change all font sizes to 12 pt font. Bold the legend title and the axes titles. Increase the size of the points on the plot to 2. Bonus: fill the points with color and have a black outline around each point.

Solution

ggplot(iris)+
  geom_point(aes(Petal.Length,Petal.Width,fill=Species),size=2,shape=21)+
  coord_fixed(ratio=1,ylim=c(0,2.75),xlim=c(0,7)) +
  scale_y_continuous(breaks=c(0,0.5,1,1.5,2,2.5)) +
  scale_x_continuous(breaks=c(0,1,2,3,4,5,6,7)) +
  scale_fill_brewer(palette = "Dark2",name="Iris Species") +
  labs(x="Petal Length (cm)", y= "Petal Width (cm)") +
  theme_bw()+
  theme(axis.text=element_text(family="Times",size=12),
        axis.title=element_text(family="Times",face="bold",size=12),
        legend.text=element_text(family="Times",size=12),
        legend.title = (element_text(family="Times",face="bold",size=12))
        )

Now, save your plot using ggsave.

Solution

ggsave("iris.tiff", width=5.5, height=3.5,units="in")