Previous labs have had you create different types of visuals for helping illustrate your data,

we have focused on the built-in graphing abilities in R, but there are many other options for

creating high-level, publication quaility figures, the most common graphing tool is ggplot

Here are some helpful links for understanding the structure of coding in ggplot:

https://ggplot2.tidyverse.org/articles/ggplot2.html

https://r-graph-gallery.com/ggplot2-package.html

PART 1: installing and loading ggplot2

library(ggplot2)

PART 2: Practicing with barnacle_data_2.csv, boxplots

In R lab 5, you worked with the barnacle dataset to look at how tide height influenced size and how two size measurements related to one another. I had you graph these things with the basic visualization tools, but let’s try and make them a bit fancier using ggplot2

Please perform the tasks below: 1. Load the “barnacle_data_2.csv” file, call it “barnacle”

barnacle <- read.csv("barnacle_data_2.csv", header = TRUE)
str(barnacle)
## 'data.frame':    191 obs. of  4 variables:
##  $ Tide.Height : chr  "H" "H" "H" "H" ...
##  $ OperculumAug: num  5.26 5.62 5.48 5.07 5.23 ...
##  $ BasalAug    : num  7.1 9.26 8.29 11.58 9.56 ...
##  $ WidthChange : num  68.019 18.658 0.977 6.366 12.214 ...
  1. Run the code chunk below, this will create a boxplot:
ggplot(barnacle, aes(x = Tide.Height, y = WidthChange)) + geom_boxplot()

3. Notice that the chart has no color and that the syntax on the axes labels is poor, we can add to our initial code to change these things, run the code chunk below:

ggplot(barnacle, aes(x = Tide.Height, y = WidthChange, fill = Tide.Height)) + geom_boxplot() + labs( x = "Tide Height", y = "Change in Width (mm)")

4. Notice how the figure now has the proper titles for the axes and the boxes are colored. One thing of note, there is now a figure legend. With respect to the figure legend, we still see the syntax error relating to the column name (we don’t want it to say Tide.Height!) and also, do we really need a figure legend if the x-axis contains the info we need? Run the two code chunks below to see how we can address this issue.

ggplot(barnacle, aes(x = Tide.Height, y = WidthChange, fill = Tide.Height)) + geom_boxplot() + 
  labs( x = "Tide Height", y = "Change in Width (mm)") +
    theme(legend.position="none")

ggplot(barnacle, aes(x = Tide.Height, y = WidthChange, fill = Tide.Height)) + geom_boxplot() + 
  labs( x = "Tide Height", y = "Change in Width (mm)", fill = "Tide Height") 

5. We’ve now seen ways in which we can change the legend information. But what if we wanted different colors? What if we didn’t like having the gray in the background? CHALLENGE: recreate the plot above but change the color of the boxes to ANYTHING YOU WANT (as long as there are 2 different colors), also, create the plot with a white background, not a gray one!

Using code from these two links will be helpful in accomplishing this! https://r-graph-gallery.com/264-control-ggplot2-boxplot-colors.html http://www.sthda.com/english/wiki/ggplot2-themes-and-background-colors-the-3-elements

ggplot(barnacle, aes(
  x = Tide.Height,
  y = WidthChange,
  fill = Tide.Height
)) +
  geom_boxplot() +
  labs(
    x = "Tide Height",
    y = "Change in Width (mm)"
  ) +
  scale_fill_manual(
    values = c("H" = "olivedrab3",
               "L" = "mediumpurple")
  ) +
  theme_bw() +
  theme(
    legend.position = "none"
  )

PART 3: Practicing with barnacle_data_2.csv, line graphs

In R Lab 5, you all plotted the relationships of two size variables. Let’s see how we can use R to make the scatter plot a bit nicer!

  1. With the “barnacle” data still in R, run the following code:
ggplot(barnacle, aes(x=OperculumAug, y=BasalAug)) + 
    geom_point()

  1. The scatter plot created above does a nice job of showing the data, but let’s show some ways in which we can make it nicer, run the code below:
ggplot(barnacle, aes(x=OperculumAug, y=BasalAug)) + 
    geom_point(color = "darkblue", shape = 3, size = 12 )

3. The scatter plot above included code to change the shape of the points, the size of the points, and the color of the points! Challenge: recreate the code above but change the color to anything you want, the size to anything you want, and the shape to a filled in square. Use the links below to look at color and shape options! http://www.sthda.com/english/wiki/ggplot2-point-shapes https://sape.inf.usi.ch/quick-reference/ggplot2/colour

ggplot(barnacle, aes(x=OperculumAug, y=BasalAug)) + 
    geom_point(color = "tomato", shape = 18, size = 5 )

  1. When we created the scatter plot in R lab 5, we want to add our least squares regression line to help describe the fit. We can add this using ggplot without ever needing to run the regression! Run the two codes below to see how we can get this to work:
ggplot(barnacle, aes(x=OperculumAug, y=BasalAug)) + 
    geom_point() +
  geom_smooth(method=lm , color="red", se=FALSE) 
## `geom_smooth()` using formula = 'y ~ x'

ggplot(barnacle, aes(x=OperculumAug, y=BasalAug)) + 
    geom_point() +
  geom_smooth(method=lm , color="red", fill="#69b3a2", se=TRUE) 
## `geom_smooth()` using formula = 'y ~ x'

  1. The above plots show that we can add the line, change the color, and even have the option of including a standard error visual!

  2. CHALLENGE: create a scatter plot for OperculumAug vs. BasalAug, but change the background to white, change the axes labels so they just say “Operculum (mm)” and “Basal Width (mm)”, the plot should also include the line of best fit and SE.

ggplot(barnacle, aes(
  x = OperculumAug,
  y = BasalAug
)) +
  geom_point(
    color = "tomato",
    shape = 18,
    size = 2
  ) +
  geom_smooth(
    method = lm,
    color = "olivedrab",
    se = TRUE
  ) +
  labs(
    x = "Operculum (mm)",
    y = "Basal Width (mm)"
  ) +
  theme_bw()
## `geom_smooth()` using formula = 'y ~ x'

PART 4: Practicing with barnacle_data_2.csv, bar graphs

What you may have noticed about the boxplot you created is that it is a little tough to see patterns and make comparisons as the boxes get flattened with some of the outliers. To create a better visual, you may want to consider plotting the mean values as bars and adding error bars to help visualize variation.

Creating a barplot in ggplot (and in R) is a little bit trickier as it involves a little manipulation. NOTE: there are other ways to create a barplot with means, I am showing you one way

  1. We need to calculate the mean and some measure of variance to plot! We used a code called aggregate() in the past to help calculate summary statistics and store them in a data table, let’s do the same with the barnacle data. The code below will create two separate datasets, one for mean and one for standard deviation:
mean_basal <- aggregate(barnacle$WidthChange, by = list(barnacle$Tide.Height), mean)
sd_basal <- aggregate(barnacle$WidthChange, by = list(barnacle$Tide.Height), sd)

2.We’ve calculated the mean and SD for this data, but they exist in separate tables! It tends to be easier to work with data when they are part of the same data table, the code below is going to merge the two data tables together into a new data table. NOTE: if you recall, the column titles from the aggregate code show up as “Group.1” and “x”, I will need to use these in the merge function below.

total_basal <- merge(mean_basal, sd_basal, by = "Group.1")
  1. The “total_basal” file now has the combined data, the only issue is that the column names are not informative. You can certainly use the output from above without changing anything, but it may be easier to change the names before creating plots. The code below rewrites the column names:
colnames(total_basal) <- c("Tide.Height", "Mean", "SD")
  1. Let’s use this new dataset to create our barplot with error bars:
ggplot(total_basal) +
  geom_bar( aes(x=Tide.Height, y=Mean), stat="identity", fill="skyblue", alpha=0.5) +
  geom_errorbar( aes(x=Tide.Height, ymin=Mean-SD, ymax=Mean+SD), width=0.4, colour="orange", alpha=0.9, size=1.5)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

  1. With the graph above, it is much easier to see patterns/differences in the data. CHALLENGE: create a bar graph for this data that has: thinner error bars, proper axes labels, a white background, and different color bars!
ggplot(total_basal, aes(
  x = Tide.Height,
  y = Mean,
  fill = Tide.Height
)) +
  geom_bar(
    stat = "identity",
    alpha = 0.7
  ) +
  geom_errorbar(
    aes(
      ymin = Mean - SD,
      ymax = Mean + SD
    ),
    width = 0.2,
    color = "purple4",
    linewidth = 0.5
  ) +
  scale_fill_manual(
    values = c(
      "H" = "lightpink",
      "L" = "yellowgreen"
    )
  ) +
  labs(
    x = "Tide Height",
    y = "Mean Change in Width (mm)"
  ) +
  theme_bw() +
  theme(
    legend.position = "none"
  )