Labels and titles in R Programming - Time & Space Complexity
When adding labels and titles in R plots, it is important to understand how the time to create these elements changes as the data grows.
We want to know how the work needed to add labels and titles scales with the size of the data.
Analyze the time complexity of the following code snippet.
x <- 1:1000
plot(x, x^2, main = "Square Numbers", xlab = "Input", ylab = "Output")
for(i in 1:length(x)) {
text(x[i], x[i]^2, labels = i, cex = 0.6)
}
This code plots points and adds a label to each point using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding text labels inside a loop.
- How many times: Once for each point in the data (n times).
As the number of points increases, the number of label additions grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 labels added |
| 100 | 100 labels added |
| 1000 | 1000 labels added |
Pattern observation: The work grows in a straight line with the number of points.
Time Complexity: O(n)
This means the time to add labels grows directly in proportion to the number of points.
[X] Wrong: "Adding labels takes the same time no matter how many points there are."
[OK] Correct: Each label requires a separate action, so more points mean more labels and more time.
Understanding how adding labels scales helps you explain performance in data visualization tasks clearly and confidently.
"What if we added labels only to every 10th point? How would the time complexity change?"