Create Line Charts in Python with Matplotlib
Learn how to build a line chart in Python using Matplotlib, from preparing data to plotting values, labeling axes, and visualizing trends step by step.
1. Step-by-Step Demonstration
Now we will create our first line chart using Python and Matplotlib.
We will use the university enrollment dataset introduced earlier.
Step 1: Install Matplotlib
Matplotlib is a Python library used to create charts and graphs.
Open your terminal or command prompt and execute:
pip install matplotlibWait until the installation is completed.
Note: If you are using Jupyter Notebook, you can run !pip install matplotlib in a notebook cell.
Step 2: Import the required library
Before using Matplotlib, we need to import it.
import matplotlib.pyplot as pltUnderstand the code:
importloads a Python library.matplotlibis the library name.pyplotprovides functions for creating charts.as pltgives us a short name to use instead of writingmatplotlib.pyplotevery time.
For example, we can write:
plt.show()Instead of writing the full library name.
Step 3: Prepare the dataset
We will store the months and enrollment values in two Python lists.
months = [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]
students = [
50, 65, 60, 80, 75, 100,
110, 95, 120, 130, 125, 150
]Understand the code:
monthsstores the names of the months.studentsstores the number of enrolled students.- Each position in the first list corresponds to the same position in the second list.
For example:
| Position | Month | Students |
|---|---|---|
| 0 | January | 50 |
| 1 | February | 65 |
| 2 | March | 60 |
| 3 | April | 80 |
Important: Both lists must contain the same number of items.
Step 4: Create a basic line chart
We will use plt.plot() to create our first line chart.
import matplotlib.pyplot as plt
months = [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]
students = [
50, 65, 60, 80, 75, 100,
110, 95, 120, 130, 125, 150
]
plt.plot(months, students)
plt.show()Understand plt.plot():
plt.plot(months, students)| Part | Meaning |
|---|---|
plt |
Matplotlib pyplot |
plot() |
Creates a line chart |
months |
X-axis data |
students |
Y-axis data |
What happens?
- Python reads the month names.
- It reads the corresponding enrollment values.
- Matplotlib places the values on the chart.
- It connects the points with lines.
plt.show()displays the chart.
Step 5: Add a chart title
A chart title tells viewers what the chart represents.
Use plt.title().
plt.plot(months, students)
plt.title("Monthly Student Enrollment")plt.show()Step 6: Add X-axis and Y-axis labels
We should describe what each axis represents.
Use:
plt.xlabel()for the horizontal axis.plt.ylabel()for the vertical axis.
plt.plot(months, students)
plt.title("Monthly Student Enrollment")
plt.xlabel("Months")
plt.ylabel("Number of Students")
plt.show()
Expected chart information:
- Title: Monthly Student Enrollment
- X-axis: Months
- Y-axis: Number of Students
Step 7: Display the chart
The function plt.show() displays the completed chart.
It is normally placed at the end of the chart code.
plt.show()Without this command, a chart may not appear in some Python environments.
Step 8: Add markers to show individual data points
A line connects data points, but we may also want to display the individual points clearly.
We can use the marker parameter.
plt.plot(months, students, marker="o")
plt.title("Monthly Student Enrollment")
plt.xlabel("Months")
plt.ylabel("Number of Students")
plt.show()Here:
marker="o"displays circular markers.- Each circle represents one month's enrollment.
Other marker examples:
| Marker | Appearance |
|---|---|
"o" |
Circle |
"s" |
Square |
"^" |
Triangle |
"D" |
Diamond |
"*" |
Star |
"x" |
Cross |
Step 9: Change line colors and styles
We can customize the appearance of the line.
plt.plot( months, students, color="green", linestyle="--", marker="o")
plt.title("Monthly Student Enrollment")
plt.xlabel("Months")
plt.ylabel("Number of Students")plt.show()Important parameters:
| Parameter | Purpose |
|---|---|
color |
Changes line color. |
linestyle |
Changes line appearance. |
marker |
Displays data points. |
Common line styles:
| Style | Appearance |
|---|---|
"-" |
Solid line |
"--" |
Dashed line |
":" |
Dotted line |
"-." |
Dash-dot line |
Common colors include:
"red", "blue", "green", "orange", "black" and "purple".
Step 10: Add gridlines
Gridlines make it easier to read numerical values.
Use plt.grid().
plt.plot(months, students, marker="o")
plt.title("Monthly Student Enrollment")
plt.xlabel("Months")
plt.ylabel("Number of Students")
plt.grid(True)plt.show()Here:
plt.grid(True)displays gridlines.- Gridlines help us compare the position of each point with the axis values.
Step 11: Add a legend
A legend identifies the data shown by a line.
We can use label inside plt.plot() and plt.legend() to display it.
plt.plot( months, students, marker="o", color="blue", label="University Enrollment")
plt.title("Monthly Student Enrollment")
plt.xlabel("Months")
plt.ylabel("Number of Students")
plt.legend()plt.grid(True)plt.show()Understand:
labelgives a name to the line.plt.legend()displays that name on the chart.
A legend becomes especially important when a chart contains multiple lines.
Step 12: Display values using annotations
Sometimes we want to show the exact numerical value beside each point.
We can use plt.annotate().
plt.plot(months, students, marker="o")
for i in range(len(months)):
plt.annotate(
students[i],
(months[i], students[i])
)
plt.title("Monthly Student Enrollment")
plt.xlabel("Months")
plt.ylabel("Number of Students")
plt.grid(True)
plt.show()Understand the new code:
len(months)returns the number of months.range()generates positions from zero to eleven.forrepeats the annotation operation for every month.students[i]gets the enrollment value at positioni.(months[i], students[i])identifies the location of the point.
Result: Every data point displays its corresponding enrollment value.
Complete example: Your first professional line chart
Now combine the concepts learned in this section.
import matplotlib.pyplot as plt
# Step 1: Prepare data
months = [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]
students = [
50, 65, 60, 80, 75, 100,
110, 95, 120, 130, 125, 150
]
# Step 2: Create line chart
plt.plot(
months,
students,
color="blue",
linestyle="-",
linewidth=2,
marker="o",
markersize=7,
label="Student Enrollment"
)
# Step 3: Add chart information
plt.title("Monthly Student Enrollment")
plt.xlabel("Month")
plt.ylabel("Number of Students")
# Step 4: Add data labels
for i in range(len(months)):
plt.annotate(
students[i],
(months[i], students[i]),
textcoords="offset points",
xytext=(0, 8),
ha="center"
)
# Step 5: Add gridlines and legend
plt.grid(True)
plt.legend()
# Step 6: Display chart
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()What have we learned?
We have created a line chart with:
- A title.
- X-axis and Y-axis labels.
- A blue connecting line.
- Circular markers.
- Data labels.
- Gridlines.
- A legend.
- Rotated month names.