Scatter plots (geom_point) in R Programming - Time & Space Complexity
When we create scatter plots using geom_point in R, the time it takes depends on how many points we draw.
We want to understand how the drawing time grows as we add more points.
Analyze the time complexity of the following code snippet.
library(ggplot2)
n <- 1000
data <- data.frame(x = rnorm(n), y = rnorm(n))
ggplot(data, aes(x = x, y = y)) +
geom_point()
This code creates a scatter plot with n points using geom_point.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each point on the plot.
- How many times: Once for each of the
npoints in the data.
As the number of points increases, the time to draw grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 point draws |
| 100 | 100 point draws |
| 1000 | 1000 point draws |
Pattern observation: Doubling the points roughly doubles the work needed to draw.
Time Complexity: O(n)
This means the time to create the scatter plot grows linearly with the number of points.
[X] Wrong: "Adding more points won't affect drawing time much because the computer is fast."
[OK] Correct: Each point requires work to draw, so more points mean more work and longer time.
Understanding how plotting time grows helps you write efficient code and explain performance in data visualization tasks.
"What if we added a smoothing line with geom_smooth? How would the time complexity change?"