Line plots in Data Analysis Python - Time & Space Complexity
When we create line plots, we want to know how the time to draw the plot changes as we add more data points.
We ask: How does the work grow when the data size grows?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
def plot_line(data):
x = np.arange(len(data))
plt.plot(x, data)
plt.show()
This code creates a line plot for a list or array of numbers by plotting each point in order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting each data point on the line plot.
- How many times: Once for each data point in the input array.
As the number of data points increases, the time to plot grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations (plot points) |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly with the number of points; doubling points doubles work.
Time Complexity: O(n)
This means the time to create the line plot grows in a straight line with the number of data points.
[X] Wrong: "Plotting a line plot takes the same time no matter how many points there are."
[OK] Correct: Each point must be drawn, so more points mean more work and more time.
Understanding how plotting time grows helps you explain performance when working with data visualization in real projects.
"What if we added multiple lines to the plot instead of one? How would the time complexity change?"