By the end of this lesson, you will be able to create a basic line chart using Python's Matplotlib library to visualize trends in numerical data.
What it is
Plotting in Python typically refers to creating visual representations of data. The most common library for this is matplotlib.pyplot. A line chart connects individual data points with straight lines, making it ideal for showing how a variable changes over time or across an ordered sequence. Key concepts include the x-axis (independent variable), y-axis (dependent variable), and the plot object which holds the graphical elements.
Why it matters
- Trend Identification: Quickly spot increases, decreases, or patterns in time-series data like stock prices or temperature.
- Data Comparison: Overlay multiple lines on one chart to compare different datasets side-by-side.
- Communication: Visuals are often more intuitive than raw tables for stakeholders who need quick insights.
- Debugging: Plotting intermediate results helps verify that your calculations behave as expected during development.
Syntax or steps
The standard workflow involves importing the library, preparing data, calling the plot function, adding labels, and displaying the result.
- Import
matplotlib.pyplot. - Create lists or arrays for x and y values.
- Call
plt.plot(x, y)to draw the line. - Add context with
plt.xlabel(),plt.ylabel(), andplt.title(). - Show the graph with
plt.show().
Example
import matplotlib.pyplot as plt
# Sample data: Months and Sales figures
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [150, 200, 180, 250, 300]
# Create the line chart
plt.plot(months, sales)
# Add labels and title
plt.xlabel('Month')
plt.ylabel('Sales (Units)')
plt.title('Monthly Sales Trend')
# Display the plot
plt.show()
Explanation: We import pyplot as plt. Two lists, months and sales, hold our categorical x-data and numerical y-data. plt.plot() draws the line connecting these points. Labels clarify what each axis represents, and plt.show() renders the window containing the chart.
Common mistakes
- Forgetting
plt.show(): Without this call, the script runs but no window appears (especially in scripts vs. notebooks). - Mismatched lengths: If
xandylists have different numbers of items, Matplotlib raises a ValueError. - Overwriting plots: Calling
plt.plot()again without clearing the figure adds to the current plot. Useplt.clf()to clear if starting fresh. - Ignoring scale: Large differences in y-values can make smaller variations invisible; consider log scales or separate charts if needed.
When to use it
Line charts are best for continuous data or ordered categories. Compare them with bar charts for discrete comparisons.
| Chart Type | Best For | Example Data |
|---|---|---|
| Line Chart | Trends over time/sequence | Temperature per hour |
| Bar Chart | Comparing distinct categories | Sales by product type |
| Scatter Plot | Correlation between two variables | Height vs. Weight |
Practice
Guided Exercise: Modify the example above to add a second line representing "Expenses" with values [100, 120, 110, 140, 160]. Ensure both lines appear on the same chart.
Challenge: Change the color of the first line to red and the second to blue using the color parameter in plt.plot().
Hint: Call plt.plot() twice before calling plt.show(). Example: plt.plot(months, sales, color='red').
Quick check
Question: What happens if you omit plt.show() when running a Python script?
Answer: The code executes without error, but the plot window does not appear because the display command was never triggered.
Summary
Matplotlib’s plt.plot() provides a simple yet powerful way to visualize trends. By pairing data lists with labeling functions, you transform raw numbers into actionable insights. Mastering this basic pattern is the foundation for more complex data visualization tasks.