Logo

How to plot two graphs in a same plot in R?

Combining two graphs in one plot is invaluable for comparing data series side by side or spotting trends that correlate. In R, you can do this conveniently with base functions or using ggplot2.

Approach 1: Base R
You can plot one dataset, then add another on top:

# Example data
x <- 1:10
y1 <- x^2
y2 <- sqrt(x)

# Create the first plot
plot(x, y1, type = "l", col = "blue", ylim = c(0, max(y1, y2)))
# Add second line to the existing plot
lines(x, y2, col = "red")

In this snippet, plot() displays the first dataset, while lines() superimposes the second. The ylim argument helps ensure both lines fit in the same y-range.

Approach 2: ggplot2
If you prefer the ggplot2 syntax, try multiple geom_ layers:

library(ggplot2)

# Use a combined dataframe or reshape it to long format
df <- data.frame(x, y1, y2)

ggplot(df, aes(x = x)) +
  geom_line(aes(y = y1), color = "blue") +
  geom_line(aes(y = y2), color = "red")

Each geom_line() layer corresponds to a different variable in the dataset, all displayed on the same coordinate system.

Pro Tips

  • Label your axes and add a legend (in base R, you can use legend(), while ggplot2 has scale_color_manual() or separate geom_line() calls).
  • Adjust colors or line types for clarity.
  • For advanced customization, consider facets (facet_wrap in ggplot2) if you need multiple subplots in one figure.

Broader Interview Prep
Plotting data in R is just one essential skill. If you’re preparing for coding interviews or wish to strengthen your algorithmic thinking, check out:

If you aspire to design efficient, large-scale systems, start with Grokking System Design Fundamentals. You can also polish your interview skills by enrolling in a Coding Mock Interview or System Design Mock Interview led by ex-FAANG engineers. For more insights, visit the DesignGurus.io YouTube channel.

CONTRIBUTOR
TechGrind