ggplot() and aes() basics in R Programming - Time & Space Complexity
When we use ggplot() and aes() to create plots, the computer does work to draw each point or shape.
We want to understand how the time to draw grows as we add more data points.
Analyze the time complexity of the following code snippet.
library(ggplot2)
data <- data.frame(x = 1:1000, y = rnorm(1000))
ggplot(data) +
aes(x = x, y = y) +
geom_point()
This code creates a scatter plot with 1000 points using ggplot2.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each point on the plot.
- How many times: Once for each data point (1000 times here).
As the number of points increases, the time to draw grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 points drawn |
| 100 | 100 points drawn |
| 1000 | 1000 points drawn |
Pattern observation: Doubling the points roughly doubles the work to draw.
Time Complexity: O(n)
This means the time to create the plot grows directly with the number of points.
[X] Wrong: "Adding more points won't affect the time much because the plot is just one picture."
[OK] Correct: Each point needs to be drawn separately, so more points mean more work and more time.
Understanding how plotting time grows helps you write efficient code when working with big data and visuals.
"What if we added a second geom layer, like geom_line()? How would the time complexity change?"