Link Search Menu Expand Document

GGPLOT2 Practice

All of these problems use the iris dataset. For the problems in the same section, you are building off the same plot code. Use online tools as needed (Google, ChatGPT) to find the answers as needed.

Section 1 - box plot

P1: Make a boxplot of petal length by iris species.

Answer P1 ggplot(iris, aes(x=Species, y=Petal.Length))+ geom_boxplot()

P2: Rename the x and y axes

Answer P2

ggplot(iris, aes(x=Species, y=Petal.Length))+

geom_boxplot()+

labs(x="Iris Species", y="Petal Length")

P3: Color the box outline and fill by iris species.

Answer P3

ggplot(iris, aes(x=Species, y=Petal.Length, fill=Species, color=Species))+

geom_boxplot()+

labs(x="Iris Species", y="Petal Length")

P4: Make the fill more transparent to be able to see the outline and median of the boxplots.

Answer P4

ggplot(iris, aes(x=Species, y=Petal.Length, fill=Species, color=Species))+

geom_boxplot(alpha=0.3)+

labs(x="Iris Species", y="Petal Length")

Note, smaller alpha is more transparent.1 = full opaque, 0 = fully transparent.

P5: Change the fill and color to custom colors. You can use any colors you want. I like this website to find colors.

Answer P5

ggplot(iris, aes(x=Species, y=Petal.Length, fill=Species, color=Species))+

geom_boxplot(alpha=0.3)+

labs(x="Iris Species", y="Petal Length")

scale_color_manual(values=c("#7b01a0","#a07b01","#01a07b"))+

scale_fill_manual(values=c("#7b01a0","#a07b01","#01a07b"))

P6: Change the color and size of the axes labels

Answer P6

ggplot(iris, aes(x=Species, y=Petal.Length, fill=Species, color=Species))+

geom_boxplot(alpha=0.3)+

labs(x="Iris Species", y="Petal Length")

scale_color_manual(values=c("#7b01a0","#a07b01","#01a07b"))+

scale_fill_manual(values=c("#7b01a0","#a07b01","#01a07b"))+

theme(axis.text = element_text(colour = "black", size = 10))

Section 2 - Dot plots/scatter plot

P7: Make a dot plot of petal length and petal with. Add linear regression lines to fit the points. Color the lines and the points by species.

Answer P7

ggplot(iris, aes(x=Petal.Width, y=Petal.Length, color=Species))+

geom_point()+

geom_smooth(method="lm")

Section 3 - Histograms

P8: Make a histogram of petal width and color the bars by species.

Answer P8 ggplot(iris, aes(x=Petal.Width, fill=Species))+ geom_histogram()