Line Plots in Matplotlib
In this lesson, you will learn how to create line plots using Matplotlib. You will understand how to plot data points, customize line styles, add markers, display multiple lines, and format your charts.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand what a line plot is and where it is used.
- Create line plots using the Matplotlib plot() function.
- Understand X-axis and Y-axis data values.
- Customize line colours, width, styles, and markers.
- Add chart titles, axis labels, grid lines, and legends.
- Display multiple data series in a single line chart.
- Save line plots in different file formats.
2. What Is a Line Plot?
A line plot is a type of chart that displays data points connected by straight lines. It is commonly used to show trends, patterns, and changes in values over a period of time.
In Matplotlib, the plot() function is used to create line plots. You provide X-axis and Y-axis values, and Matplotlib connects the corresponding data points.
Example: Monthly Sales Report
Suppose a company wants to understand its monthly sales. It has sales values for January, February, March, April, and May. A line plot can show how sales increase or decrease during these months.
The months are displayed on the X-axis, while the sales values are displayed on the Y-axis.
3. Basic Syntax of the plot() Function
The plot() function is the main function used to create a line chart. It accepts X-axis and Y-axis values as its basic arguments.
Syntax
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
| Parameter | Description |
|---|---|
| x | Values displayed along the X-axis. |
| y | Values displayed along the Y-axis. |
| plt.plot() | Creates the line plot using the supplied data. |
| plt.show() | Displays the created chart. |
4. Creating Your First Line Plot
Let's create a simple line plot using a list of days and their corresponding sales values.
Example: Weekly Sales
import matplotlib.pyplot as plt
days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday"]
sales = [100, 150, 130, 180, 220]
plt.plot(days, sales)
plt.title("Weekly Sales Report")
plt.xlabel("Days")
plt.ylabel("Sales")
plt.show()
Explanation:
- We import pyplot from Matplotlib.
- The days list contains X-axis values.
- The sales list contains Y-axis values.
- plot() creates the line chart.
- title(), xlabel(), and ylabel() add chart information.
- show() displays the chart.
5. Customizing Line Colour and Width
Matplotlib allows you to customize the appearance of a line. You can change its colour and thickness using the color and linewidth parameters.
Example: Changing Colour and Width
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(
x,
y,
color="red",
linewidth=3
)
plt.title("Customized Line Plot")
plt.show()
| Parameter | Description | Example |
|---|---|---|
| color | Changes the colour of the line. | color="red" |
| linewidth | Changes the thickness of the line. | linewidth=3 |
6. Using Different Line Styles
The linestyle parameter controls the pattern of the line. Matplotlib supports solid, dashed, dotted, and dash-dot styles.
| Line Style | Value | Description |
|---|---|---|
| Solid | - | A continuous line. |
| Dashed | -- | A line made of dashes. |
| Dotted | : | A line made of dots. |
| Dash-dot | -. | A combination of dashes and dots. |
Example
plt.plot(
x,
y,
color="green",
linestyle="--",
linewidth=2
)
plt.show()
7. Adding Markers to a Line Plot
Markers are symbols displayed at individual data points. They help identify the exact positions of values on a line chart.
| Marker | Value | Description |
|---|---|---|
| Circle | o | Displays a circle marker. |
| Square | s | Displays a square marker. |
| Triangle | ^ | Displays a triangle marker. |
| Star | * | Displays a star marker. |
| Plus | + | Displays a plus marker. |
| Diamond | D | Displays a diamond marker. |
Example
plt.plot(
x,
y,
marker="o",
markersize=8,
color="blue"
)
plt.show()
8. Adding Titles, Axis Labels, Grid, and Legend
A good chart should clearly explain the information it displays. Matplotlib provides functions to add titles, labels, grid lines, and legends.
| Function | Purpose |
|---|---|
| plt.title() | Adds a title to the chart. |
| plt.xlabel() | Adds a label to the X-axis. |
| plt.ylabel() | Adds a label to the Y-axis. |
| plt.grid() | Displays grid lines. |
| plt.legend() | Displays the legend. |
Example
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]
revenue = [120, 150, 135, 180, 210]
plt.plot(
months,
revenue,
color="blue",
marker="o",
label="Revenue"
)
plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue")
plt.grid(True)
plt.legend()
plt.show()
9. Plotting Multiple Lines
Matplotlib allows you to display more than one line in the same chart. You can call plot() multiple times and use different colours and labels to compare different data series.
Example: Comparing Product Sales
Suppose a company wants to compare the monthly sales of Product A and Product B. Both data series can be displayed in one chart.
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]
product_a = [100, 120, 150, 140, 180]
product_b = [90, 110, 130, 160, 170]
plt.plot(
months,
product_a,
color="blue",
marker="o",
label="Product A"
)
plt.plot(
months,
product_b,
color="red",
marker="s",
label="Product B"
)
plt.title("Product Sales Comparison")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.grid(True)
plt.show()
10. Saving a Line Plot
After creating a chart, you can save it as an image or document using the savefig() function.
Example: Saving a Chart
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y, marker="o")
plt.title("My Line Chart")
plt.savefig(
"line_chart.png",
dpi=300,
bbox_inches="tight"
)
plt.show()
| Parameter | Description |
|---|---|
| line_chart.png | Name and file format of the saved chart. |
| dpi=300 | Sets the output resolution. |
| bbox_inches="tight" | Adjusts the saved bounding box to fit the chart content. |
11. Common Mistakes While Creating Line Plots
Beginners may face some common problems while creating line charts. Understanding these issues helps you write correct Matplotlib code.
| Common Mistake | Solution |
|---|---|
| X and Y values have different lengths. | Make sure both data sequences have compatible lengths. |
| Chart is not displayed. | Call plt.show() in a normal Python script. |
| Legend is not visible. | Provide labels in plot() and call plt.legend(). |
| Chart is difficult to understand. | Add a title, axis labels, and grid lines. |
| Multiple lines look similar. | Use different colours, markers, or line styles. |
12. Practical Activity
Task: Create a Monthly Temperature Chart
Create a line plot to display the temperature for six months. Follow the instructions below:
- Create a list containing six month names.
- Create a second list containing temperature values.
- Use plt.plot() to create the line chart.
- Set the line colour to red.
- Add circle markers to the data points.
- Add a chart title and axis labels.
- Enable grid lines and display the chart.
- Save the chart as temperature.png.
Starter Code
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
temperature = [18, 21, 25, 30, 33, 29]
# Create your line plot here
plt.show()
13. Practice Questions
Test your understanding of line plots:
- What is a line plot?
- Which Matplotlib function is used to create a line plot?
- What is the purpose of X-axis and Y-axis values?
- How can you change the colour of a line?
- Which parameter controls the thickness of a line?
- What is the purpose of the marker parameter?
- Name four different line styles available in Matplotlib.
- How can you display multiple lines in one chart?
- What is the purpose of plt.legend()?
- Which function is used to save a line plot?
Summary
In this lesson, you learned how to create and customize line plots using Matplotlib. You explored the plot() function, X-axis and Y-axis values, line colours, line styles, markers, chart labels, legends, and multiple data series.
- Use plt.plot() to create a line plot.
- Use color and linewidth to customize line appearance.
- Use linestyle to change the line pattern.
- Use marker to highlight individual data points.
- Use title(), xlabel(), and ylabel() to describe the chart.
- Use grid() and legend() to improve chart readability.
- Use savefig() to save the chart.
- Use show() to display the chart.