0
0
R-programmingHow-ToBeginner · 3 min read

How to Create Plot Using ggplot2 in R: Simple Guide

To create a plot using ggplot2, start by calling ggplot() with your data and aesthetic mappings inside aes(). Then add layers like geom_point() or geom_line() to specify the type of plot you want.
📐

Syntax

The basic syntax of ggplot2 involves three parts:

  • ggplot(data, aes()): Sets the data and maps variables to visual properties.
  • geom_*: Adds the type of plot layer, like points or lines.
  • + operator: Combines layers to build the plot step-by-step.
r
ggplot(data = your_data, aes(x = x_variable, y = y_variable)) +
  geom_point()
💻

Example

This example shows how to create a scatter plot using the built-in mtcars dataset, plotting miles per gallon against horsepower.

r
library(ggplot2)

ggplot(data = mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  labs(title = "Scatter plot of MPG vs Horsepower", x = "Horsepower", y = "Miles per Gallon")
Output
[A scatter plot appears showing points scattered with horsepower on the x-axis and miles per gallon on the y-axis]
⚠️

Common Pitfalls

Common mistakes include:

  • Not loading the ggplot2 library before use.
  • Forgetting to map variables inside aes(), which means the plot won't show data correctly.
  • Using + at the end of a line without continuing the plot code on the next line.

Here is an example of a wrong and right way:

r
# Wrong: missing aes mapping
library(ggplot2)
ggplot(mtcars) +
  geom_point(aes(x = hp, y = mpg))  # This will work but is less common

# Right: correct aes mapping

library(ggplot2)
ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point()
📊

Quick Reference

FunctionPurpose
ggplot(data, aes())Start a plot with data and aesthetic mappings
geom_point()Add scatter plot points
geom_line()Add lines connecting points
labs(title, x, y)Add labels and title
theme()Customize plot appearance

Key Takeaways

Always load ggplot2 with library(ggplot2) before plotting.
Use ggplot(data, aes(x, y)) to set data and map variables.
Add layers like geom_point() to specify plot type.
Use + to combine layers and build the plot step-by-step.
Check that variables are inside aes() to display data correctly.