Plot

Please execute the following code snippet before proceeding with the rest of the exercises.

set.seed(040197)
x = 1:100 + rnorm(100, mean = 6, sd = 19)
y = 1:100



  1. Create a scatter plot using the x and y vectors generated earlier.

  1. Set the labels for the x and y axes as “X values” and “Y values”, and add the title “Making a Scatter Plot Example”.

  1. Add margin text on the right side of your plot with your first and last name.

  1. Use mtext() and paste() (or paste0(), search for the difference between the two) to add margin text at the top of the plot (“Today is” followed by the current date).
    You can use paste() as the ‘text’ argument in mtext().

    HINT: mtext(side = 3, text = paste(...)); to retrieve the current date, use the Sys.Date() function, which can be directly inserted into the paste() function.

  1. The cor() function calculates the correlation between two vectors. Pearson’s correlation measures the linear relationship (dependence) between two variables, X and Y.
    Try using the cor() function with the x and y variables

  1. Try using mtext(), cor(), and paste() to display the correlation coefficient on your scatter plot.

  1. Often, it is useful to approximate double values, as we do not need many digits after the decimal point (also for visualization purposes).
    Try approximating the correlation value to two decimal places using the round() function. Then, explore what floor() and ceiling() do.

  1. Modify the shape and color of the points on the scatter plot.

  1. Try different values for the pch argument in your plot() command and explore the col= and bg= parameters accordingly.

  1. Create a histogram of the x variable. A histogram is a graphical representation of the data distribution.

  1. Modify the color of the histogram.

  1. Create a boxplot of the y variable. Remember to set notch = TRUE.

  1. Create boxplots of the x and y vectors on the same plot, using two different colors for each.

  1. In the boxplot, use the horizontal = TRUE argument.

  1. Create multiple plots using par(mfrow = c(2, 1)):

    • Run par(mfrow = c(2, 1)) to set up the plotting layout.

    • Create a boxplot of the y variable.

    • Create a histogram of the x variable.


  1. Do the same as above, but this time use par(mfrow = c(1, 2))

  1. Save your last figure as PDF.

  1. You can create a scatter plot that shows the density of points instead of plotting the points themselves. This is useful when you want to see if your points accumulate around certain values or if you have too many points, making it difficult to distinguish their precise locations.

    By using the smoothScatter() function instead of plot(x, y), you can visualize the densities. Try it out!

    Then, use colramp = colorRampPalette(c("white", "blue", "green", "yellow", "red")) to apply custom colors.
    Feel free to adjust the colors to your liking and save the plot as a PDF.