QUESTION: “How do I make a scatterplot in R when my data is in two vectors?”

If you have data in two separate vectors, say X and Y, how do you make a scatterplot using base R?

Data

We’ll use the “palmerpenguins” packages (https://allisonhorst.github.io/palmerpenguins/) to address this question. You’ll need to install the package with install.packages(“palmerpenguins”) if you have not done so before, call library(““palmerpenguins”), and load the data with data(penguins)

#install.packages("palmerpenguins")
library(palmerpenguins)
data(penguins)

Let’s put two columns from this dataframe into vectors called X and Y. (Don’t worry if you don’t know how to do this, just run the code).

X <- penguins$body_mass_g
Y <-penguins$bill_length_mm

Making a scatterplot from two vectors

We make scatterplots in R with the plot() function.

plot(Y ~ X)

We can label the x and y axis with xlab = … and ylab = …

plot(Y ~ X, 
     xlab = "Body mass (g)",
     ylab = "Bill length (mm)")

Additional Reading

For more information on this topic, see: https://www.statmethods.net/graphs/scatterplot.html

Keywords:

  1. plot()
  2. plot
  3. scatterplot
  4. scatter plot
  5. xlab
  6. ylabs
  7. data visualization
  8. palmerpenguins