Python Matplotlib

Matplotlib is one of the most popular data visualization libraries in Python. It helps to create charts, graphs, and plots from data. Whether the data is simple numbers or complex scientific results, Matplotlib can turn it into a visual picture that is easy to understand.

Think of Matplotlib as a digital graph paper where numbers are converted into colorful, readable charts using just a few lines of Python code.

Table of Contents

  1. What is Matplotlib?
  2. Installing Matplotlib
  3. Importing Matplotlib
  4. First Plot – Line Chart
  5. Adding Title and Labels
  6. Customizing Line Color and Style
  7. Adding Markers to a Plot
  8. Multiple Lines on a Single Plot
  9. Adding a Legend
  10. Bar Chart
  11. Horizontal Bar Chart
  12. Pie Chart
  13. Scatter Plot
  14. Histogram
  15. Subplots – Multiple Plots Together
  16. Changing Figure Size
  17. Adding Grid Lines
  18. Saving a Plot to a File
  19. Annotating a Plot
  20. Stacked Bar Chart
  21. Area Chart (Fill Between)
  22. Customizing Axis Ticks
  23. Setting Axis Limits
  24. Twin Axes – Two Y-Axes
  25. Quick Reference Cheat Sheet

1. What is Matplotlib?

Matplotlib is a Python library used to draw graphs and charts. It was created by John D. Hunter in 2003. The name comes from MATLAB, a popular mathematical software, and Matplotlib was designed to work in a similar way but inside Python.

Matplotlib is widely used in:

  • Data Science and Machine Learning
  • Scientific Research
  • Business Reports and Dashboards
  • Academic Projects

What Can Matplotlib Create?

Chart TypeUsed For
Line ChartShowing trends over time
Bar ChartComparing values across categories
Pie ChartShowing percentage distribution
Scatter PlotFinding relationships between two values
HistogramShowing frequency/distribution of data
SubplotsShowing multiple charts side by side

2. Installing Matplotlib

Before using Matplotlib, it needs to be installed. Open the terminal or command prompt and run the following command:

pip install matplotlib

If Python is installed via Anaconda, Matplotlib is already included. To verify the installation, open Python and run:

import matplotlib
print(matplotlib.__version__)

If no error appears and a version number is printed, the installation is successful.

Note: Matplotlib requires Python 3.6 or above. Most modern Python installations meet this requirement.

3. Importing Matplotlib

Matplotlib has many modules inside it. The most commonly used module is pyplot. It provides a simple interface to create plots quickly.

The standard way to import Matplotlib is:

import matplotlib.pyplot as plt

Here, plt is just a short nickname (alias) for matplotlib.pyplot. This makes typing easier. Instead of writing matplotlib.pyplot.plot() every time, just write plt.plot().

Understanding the Import Alias

Full NameAliasWhy Use Alias?
matplotlib.pyplotpltShorter and faster to type
numpynpStandard convention in data science

4. First Plot – Line Chart

A Line Chart is the most basic plot. It draws a line by connecting a series of data points. This is perfect for showing how something changes over time, like daily temperatures or monthly sales.

Syntax

plt.plot(x, y)
plt.show()

Example – Plot of Student Marks Over 5 Weeks

import matplotlib.pyplot as plt

weeks = [1, 2, 3, 4, 5]
marks = [55, 60, 70, 65, 80]

plt.plot(weeks, marks)
plt.show()

How This Works

  • weeks is the data for the X-axis (horizontal)
  • marks is the data for the Y-axis (vertical)
  • plt.plot() draws the line
  • plt.show() displays the chart on screen
Tip: Always call plt.show() at the end. Without it, the chart will not appear in most environments.

5. Adding Title and Labels

A chart without a title or labels is like a book without a name. The title tells what the chart is about and labels explain what the X and Y axes represent.

Functions Used

FunctionWhat It Does
plt.title("text")Adds a title at the top of the chart
plt.xlabel("text")Adds a label to the X-axis
plt.ylabel("text")Adds a label to the Y-axis

Example – Monthly Rainfall Chart

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5, 6]
rainfall = [80, 50, 60, 90, 110, 75]

plt.plot(months, rainfall)
plt.title("Monthly Rainfall in a City")
plt.xlabel("Month Number")
plt.ylabel("Rainfall (mm)")
plt.show()

Now the chart has a title and both axes are labeled. Anyone reading the chart can immediately understand what the data represents without needing any extra explanation.

6. Customizing Line Color and Style

By default, Matplotlib draws a simple blue line. The appearance of the line can be changed using extra parameters inside plt.plot().

Common Parameters

ParameterDescriptionExample Value
colorSets line color"red", "green", "#FF5733"
linestyle or lsSets line pattern"-", "--", "-.", ":"
linewidth or lwSets line thickness1, 2, 3 (number)

Line Style Options

Style CodeLine Type
"-"Solid line (default)
"--"Dashed line
"-."Dash-dot line
":"Dotted line

Example – Customized Temperature Line Chart

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
temperature = [30, 32, 28, 35, 33]

plt.plot(days, temperature, color="red", linestyle="--", linewidth=2)
plt.title("Daily Temperature")
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.show()

Here the line is red, dashed, and slightly thicker than the default. These small changes make the chart much more readable and visually clear.

7. Adding Markers to a Plot

Markers are small symbols placed at each data point on the line. They help to clearly see where each value is plotted on the chart.

Common Marker Styles

Marker CodeShape
"o"Circle
"s"Square
"^"Triangle (up)
"D"Diamond
"*"Star
"+"Plus
"x"Cross

Example – Sales Data with Markers

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5]
sales = [200, 250, 180, 300, 270]

plt.plot(months, sales, marker="o", color="blue", linewidth=2)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales (units)")
plt.show()

Combining Color, Marker, and Line Style in One Short Code

Matplotlib also supports a shorthand format where color, marker, and line style are combined into a single string:

plt.plot(months, sales, "ro--")
# "r" = red color, "o" = circle marker, "--" = dashed line

8. Multiple Lines on a Single Plot

It is common to compare two or more datasets on the same chart. For example, comparing the sales of two products over several months. This is done by calling plt.plot() multiple times before calling plt.show().

Example – Comparing Scores of Two Students

import matplotlib.pyplot as plt

tests = [1, 2, 3, 4, 5]
alice = [70, 75, 80, 78, 90]
bob   = [60, 65, 70, 72, 68]

plt.plot(tests, alice, color="blue", marker="o")
plt.plot(tests, bob,   color="orange", marker="s")
plt.title("Test Score Comparison")
plt.xlabel("Test Number")
plt.ylabel("Score")
plt.show()

Each plt.plot() call adds one line to the chart. Both lines appear in the same figure making comparison easy.

9. Adding a Legend

When there are multiple lines on a chart, a legend is needed to identify which line belongs to which dataset. The legend is a small box that appears on the chart showing line colors along with their labels.

Steps to Add a Legend

  1. Add a label parameter inside each plt.plot() call
  2. Call plt.legend() before plt.show()

Example – Score Comparison with Legend

import matplotlib.pyplot as plt

tests = [1, 2, 3, 4, 5]
alice = [70, 75, 80, 78, 90]
bob   = [60, 65, 70, 72, 68]

plt.plot(tests, alice, color="blue",   marker="o", label="Alice")
plt.plot(tests, bob,   color="orange", marker="s", label="Bob")
plt.title("Test Score Comparison")
plt.xlabel("Test Number")
plt.ylabel("Score")
plt.legend()
plt.show()

Legend Position Options

The legend can be placed at a specific location using the loc parameter:

plt.legend(loc="upper left")
plt.legend(loc="lower right")
plt.legend(loc="best")       # Matplotlib picks the best position automatically

10. Bar Chart

A Bar Chart uses rectangular bars to compare values across different categories. The height of each bar shows the value of that category. Bar charts are ideal when comparing items side by side.

Syntax

plt.bar(x, height)

Example – Number of Books Read by Each Person

import matplotlib.pyplot as plt

names  = ["Alice", "Bob", "Carol", "David"]
books  = [5, 8, 3, 10]

plt.bar(names, books, color="steelblue")
plt.title("Books Read in a Month")
plt.xlabel("Person")
plt.ylabel("Number of Books")
plt.show()

Customizing Bar Width and Color

plt.bar(names, books, color=["red", "green", "blue", "orange"], width=0.5)

The width parameter controls how wide each bar is. The default value is 0.8. Setting it to 0.5 makes the bars slightly thinner.

Adding Value Labels on Bars

import matplotlib.pyplot as plt

names = ["Alice", "Bob", "Carol", "David"]
books = [5, 8, 3, 10]

bars = plt.bar(names, books, color="steelblue")

for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width() / 2, height + 0.1,
             str(height), ha="center", va="bottom")

plt.title("Books Read in a Month")
plt.xlabel("Person")
plt.ylabel("Number of Books")
plt.show()

This loop adds the exact number on top of each bar, making the chart much easier to read at a glance.

11. Horizontal Bar Chart

A Horizontal Bar Chart is the same as a regular bar chart but the bars grow sideways instead of upward. It is useful when category names are long and do not fit well on the X-axis.

Syntax

plt.barh(y, width)

Example – Department-Wise Employee Count

import matplotlib.pyplot as plt

departments = ["HR", "Finance", "Engineering", "Marketing"]
employees   = [15, 20, 50, 25]

plt.barh(departments, employees, color="teal")
plt.title("Employees per Department")
plt.xlabel("Number of Employees")
plt.ylabel("Department")
plt.show()

Notice that plt.barh() is used instead of plt.bar(). The axes are also swapped — the categories go on the Y-axis and values on the X-axis.

12. Pie Chart

A Pie Chart is a circular chart divided into slices. Each slice represents a portion of the total. It is best used when showing how a whole is split into parts — for example, how a budget is divided among different expenses.

Syntax

plt.pie(sizes, labels=labels)

Example – Monthly Budget Distribution

import matplotlib.pyplot as plt

categories = ["Rent", "Food", "Transport", "Entertainment"]
amounts    = [40, 30, 15, 15]

plt.pie(amounts, labels=categories, autopct="%1.1f%%")
plt.title("Monthly Budget Distribution")
plt.show()

Key Parameters

ParameterDescription
autopct="%1.1f%%"Shows percentage on each slice
explodePulls one slice away from the center to highlight it
startangleRotates the starting position of the first slice
colorsSets custom colors for each slice
shadow=TrueAdds a shadow effect below the pie

Example – Highlighting a Slice with Explode

import matplotlib.pyplot as plt

categories = ["Rent", "Food", "Transport", "Entertainment"]
amounts    = [40, 30, 15, 15]
explode    = [0.1, 0, 0, 0]   # Pull the first slice outward

plt.pie(amounts, labels=categories, autopct="%1.1f%%",
        explode=explode, shadow=True, startangle=90)
plt.title("Monthly Budget – Rent is Highlighted")
plt.show()

The explode list has the same number of items as the data. A value of 0.1 for the first item ("Rent") pulls that slice slightly outward to draw attention to it.

13. Scatter Plot

A Scatter Plot places individual dots on the chart for each data point. It is used to discover relationships (or patterns) between two variables. For example, does studying more hours lead to better marks? A scatter plot can visually answer that question.

Syntax

plt.scatter(x, y)

Example – Study Hours vs Exam Score

import matplotlib.pyplot as plt

study_hours = [1, 2, 3, 4, 5, 6, 7, 8]
exam_score  = [40, 50, 55, 65, 70, 78, 85, 92]

plt.scatter(study_hours, exam_score, color="purple")
plt.title("Study Hours vs Exam Score")
plt.xlabel("Study Hours")
plt.ylabel("Exam Score")
plt.show()

Customizing Dot Size and Transparency

plt.scatter(study_hours, exam_score, 
            color="purple", 
            s=100,       # dot size
            alpha=0.7)   # transparency (0 = invisible, 1 = fully solid)

The s parameter sets the size of the dots and alpha controls how transparent they are. Transparency is helpful when many dots overlap each other.

14. Histogram

A Histogram looks similar to a bar chart but it is used for a completely different purpose. A histogram shows the frequency distribution of numerical data — meaning it answers "how many values fall within each range?"

For example: If 30 students took a test, a histogram can show how many students scored between 0-20, 20-40, 40-60, 60-80, and 80-100.

Syntax

plt.hist(data, bins=number_of_intervals)

Example – Distribution of Test Scores

import matplotlib.pyplot as plt

scores = [45, 55, 60, 62, 65, 68, 70, 72, 73, 75,
          76, 78, 80, 82, 85, 87, 88, 90, 92, 95]

plt.hist(scores, bins=5, color="skyblue", edgecolor="black")
plt.title("Distribution of Test Scores")
plt.xlabel("Score Range")
plt.ylabel("Number of Students")
plt.show()

Understanding the bins Parameter

bins valueEffect
Small (e.g., 5)Fewer, wider bars – less detail
Large (e.g., 20)More, narrower bars – more detail
List (e.g., [40,60,80,100])Custom bin boundaries

15. Subplots – Multiple Plots Together

Sometimes it is useful to display more than one chart in the same window side by side or in a grid. This is done using subplots. The function plt.subplot(rows, cols, index) divides the figure into a grid and selects which cell to draw in.

Understanding subplot(rows, cols, index)

ParameterMeaning
rowsNumber of rows in the grid
colsNumber of columns in the grid
indexWhich cell to use (starts from 1, left to right, top to bottom)

Example – Two Charts Side by Side

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5]
income = [3000, 3500, 4000, 3800, 4500]
expense = [2000, 2200, 1900, 2500, 2100]

# First chart (left)
plt.subplot(1, 2, 1)
plt.plot(months, income, color="green", marker="o")
plt.title("Monthly Income")
plt.xlabel("Month")
plt.ylabel("Amount ($)")

# Second chart (right)
plt.subplot(1, 2, 2)
plt.plot(months, expense, color="red", marker="s")
plt.title("Monthly Expenses")
plt.xlabel("Month")
plt.ylabel("Amount ($)")

plt.tight_layout()
plt.show()

plt.tight_layout() is called at the end to automatically adjust spacing between the charts so they do not overlap.

Example – 2×2 Grid of Charts

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

plt.subplot(2, 2, 1)
plt.plot(x, [1, 4, 9, 16, 25], color="blue")
plt.title("Squares")

plt.subplot(2, 2, 2)
plt.bar(x, [5, 3, 8, 6, 2], color="orange")
plt.title("Bar Chart")

plt.subplot(2, 2, 3)
plt.scatter(x, [2, 5, 1, 7, 4], color="purple")
plt.title("Scatter Plot")

plt.subplot(2, 2, 4)
plt.plot(x, [10, 8, 6, 4, 2], color="green", linestyle="--")
plt.title("Decreasing Line")

plt.tight_layout()
plt.show()

16. Changing Figure Size

The default chart size in Matplotlib is quite small. For presentations or reports, a larger chart is often needed. The figure size is controlled using plt.figure(figsize=(width, height)).

The values are in inches. The default size is (6.4, 4.8) inches.

Example – Wide Chart for Better Visibility

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
sales  = [100, 120, 130, 110, 150, 170, 160, 180, 190, 200, 210, 230]

plt.figure(figsize=(12, 5))   # wide and shorter
plt.plot(months, sales, color="navy", marker="o")
plt.title("Annual Sales Performance")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

The figure size must be set before any plotting commands. Calling plt.figure() after plt.plot() will create a separate blank figure.

17. Adding Grid Lines

Grid lines are horizontal and vertical lines in the background of the chart. They make it easier to read exact values from the chart, especially when the lines are far from the axes.

Enabling the Grid

plt.grid(True)

Example – Temperature Chart with Grid

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5, 6, 7]
temperature = [30, 32, 29, 35, 33, 28, 31]

plt.plot(days, temperature, color="crimson", marker="D", linewidth=2)
plt.title("Weekly Temperature")
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.grid(True)
plt.show()

Customizing the Grid

# Show only horizontal grid lines
plt.grid(True, axis="y")

# Customize color, style, and transparency
plt.grid(True, color="gray", linestyle="--", linewidth=0.5, alpha=0.7)

18. Saving a Plot to a File

Instead of only viewing a chart on screen, it can be saved directly to a file in formats like PNG, JPG, or PDF. The function used is plt.savefig().

Syntax

plt.savefig("filename.png")
Important: Always call plt.savefig() before plt.show(). Calling it after plt.show() will save a blank image because the figure is cleared after being displayed.

Example – Save a Line Chart as PNG

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]

plt.plot(x, y, color="teal", marker="o")
plt.title("Simple Line Chart")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")

plt.savefig("line_chart.png", dpi=150, bbox_inches="tight")
plt.show()

savefig Parameters

ParameterDescription
dpiResolution (dots per inch). Higher value = better quality. Default is 100.
bbox_inches="tight"Removes extra white space around the chart when saving
File formatDetermined by file extension: .png, .jpg, .pdf, .svg

19. Annotating a Plot

Annotation means adding text or arrows directly on the chart to highlight a specific data point or area. It is useful to draw attention to a maximum value, a critical threshold, or an important event.

Method 1 – Adding Simple Text with plt.text()

plt.text(x_position, y_position, "Your text here")

Method 2 – Adding an Arrow with plt.annotate()

plt.annotate("Important Point",
             xy=(x_data, y_data),           # where the arrow points
             xytext=(x_text, y_text),        # where the text appears
             arrowprops=dict(arrowstyle="->"))

Example – Highlighting the Highest Sales Month

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5, 6]
sales  = [200, 220, 210, 300, 250, 280]

plt.plot(months, sales, marker="o", color="blue")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.annotate("Highest Sales",
             xy=(4, 300),
             xytext=(4.5, 260),
             arrowprops=dict(arrowstyle="->", color="red"),
             color="red")

plt.show()

20. Stacked Bar Chart

A Stacked Bar Chart is a bar chart where multiple data sets are stacked on top of each other within the same bar. It is useful to compare both individual parts and the total at the same time.

Example – Sales of Two Products Stacked

import matplotlib.pyplot as plt

months   = ["Jan", "Feb", "Mar", "Apr", "May"]
product_a = [100, 120, 130, 140, 160]
product_b = [80,  90,  85,  110, 100]

plt.bar(months, product_a, label="Product A", color="steelblue")
plt.bar(months, product_b, bottom=product_a, label="Product B", color="coral")

plt.title("Monthly Sales – Stacked")
plt.xlabel("Month")
plt.ylabel("Sales (units)")
plt.legend()
plt.show()

The key here is the bottom parameter in the second plt.bar() call. It tells Matplotlib to start drawing the second bars from the top of the first bars, creating the stacked effect.

21. Area Chart (Fill Between)

An Area Chart is like a line chart but the area between the line and the X-axis is filled with color. It is useful for showing the volume or magnitude of a value over time.

Function Used

plt.fill_between(x, y)

Example – Website Traffic Over a Week

import matplotlib.pyplot as plt

days    = [1, 2, 3, 4, 5, 6, 7]
visitors = [200, 350, 300, 450, 500, 420, 480]

plt.plot(days, visitors, color="navy")
plt.fill_between(days, visitors, alpha=0.3, color="skyblue")
plt.title("Daily Website Visitors")
plt.xlabel("Day of the Week")
plt.ylabel("Number of Visitors")
plt.grid(True, linestyle="--", alpha=0.5)
plt.show()

Filling Between Two Lines

import matplotlib.pyplot as plt

x      = [1, 2, 3, 4, 5]
upper  = [10, 12, 15, 13, 16]
lower  = [5,  6,  7,  6,  8]

plt.plot(x, upper, label="Upper", color="green")
plt.plot(x, lower, label="Lower", color="red")
plt.fill_between(x, lower, upper, alpha=0.2, color="yellow")
plt.title("Range Between Upper and Lower Values")
plt.legend()
plt.show()

22. Customizing Axis Ticks

Ticks are the small marks along the axes that indicate values. By default, Matplotlib chooses tick positions automatically. These can be changed using plt.xticks() and plt.yticks().

Example – Custom X-Axis Labels

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5, 6]
sales  = [300, 400, 350, 500, 450, 600]

plt.plot(months, sales, marker="o", color="green")
plt.title("Bimonthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.xticks([1, 2, 3, 4, 5, 6],
           ["Jan", "Feb", "Mar", "Apr", "May", "Jun"])

plt.show()

Rotating Tick Labels

When category names are long and overlap each other, rotating them can solve the problem:

plt.xticks(rotation=45)    # rotate 45 degrees
plt.xticks(rotation=90)    # rotate 90 degrees (fully vertical)

23. Setting Axis Limits

By default, Matplotlib automatically sets the range of values on each axis. To zoom into a specific range or show a wider range, the limits can be set manually using plt.xlim() and plt.ylim().

Syntax

plt.xlim(min_value, max_value)
plt.ylim(min_value, max_value)

Example – Zoom Into a Specific Range

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

plt.plot(x, y, color="purple", marker="o")
plt.title("Squares – Zoomed In")
plt.xlabel("Number")
plt.ylabel("Square")

plt.xlim(2, 8)    # show only x values from 2 to 8
plt.ylim(0, 70)   # show only y values from 0 to 70

plt.show()

24. Twin Axes – Two Y-Axes

Sometimes two datasets have very different value ranges and need separate Y-axes to be meaningful. For example, plotting temperature (0–50°C) and rainfall (0–300mm) on the same chart. Using a single Y-axis would make one of the lines almost flat.

The solution is twin axes — one Y-axis on the left and another on the right.

Example – Temperature and Rainfall on the Same Chart

import matplotlib.pyplot as plt

months      = [1, 2, 3, 4, 5, 6]
temperature = [22, 25, 30, 35, 33, 28]
rainfall    = [80, 60, 40, 20, 50, 90]

fig, ax1 = plt.subplots()

# Left Y-axis for temperature
ax1.plot(months, temperature, color="red", marker="o", label="Temp (°C)")
ax1.set_xlabel("Month")
ax1.set_ylabel("Temperature (°C)", color="red")

# Right Y-axis for rainfall
ax2 = ax1.twinx()
ax2.bar(months, rainfall, color="skyblue", alpha=0.5, label="Rainfall (mm)")
ax2.set_ylabel("Rainfall (mm)", color="blue")

plt.title("Temperature and Rainfall")
plt.show()

ax1.twinx() creates a second axis that shares the same X-axis but has an independent Y-axis on the right side.

25. Quick Reference Cheat Sheet

Below is a summary of all the key Matplotlib functions covered in this guide.

Basic Plotting

FunctionDescription
plt.plot(x, y)Draw a line chart
plt.bar(x, y)Draw a vertical bar chart
plt.barh(x, y)Draw a horizontal bar chart
plt.scatter(x, y)Draw a scatter plot
plt.pie(sizes)Draw a pie chart
plt.hist(data, bins)Draw a histogram
plt.fill_between(x, y)Draw an area chart

Chart Customization

FunctionDescription
plt.title("text")Add chart title
plt.xlabel("text")Add X-axis label
plt.ylabel("text")Add Y-axis label
plt.legend()Show legend
plt.grid(True)Show grid lines
plt.figure(figsize=(w, h))Set chart size
plt.xticks()Customize X-axis ticks
plt.yticks()Customize Y-axis ticks
plt.xlim(min, max)Set X-axis range
plt.ylim(min, max)Set Y-axis range
plt.annotate()Add annotation with arrow
plt.text()Add plain text on chart

Output Functions

FunctionDescription
plt.show()Display the chart on screen
plt.savefig("file.png")Save chart to a file
plt.tight_layout()Auto-adjust spacing for subplots
plt.clf()Clear the current figure
plt.close()Close the chart window

plot() Style Shortcuts

Shorthand CodeMeaning
"r"Red solid line
"b--"Blue dashed line
"go"Green circles (no line)
"ks-"Black squares with solid line
"r^--"Red triangles with dashed line

Summary

Matplotlib is a powerful yet beginner-friendly library for creating all kinds of charts and graphs in Python. Starting with a simple line chart and gradually moving towards histograms, pie charts, subplots, and twin axes gives a solid foundation for data visualization.

The key workflow in Matplotlib is always the same:

  1. Import Matplotlib: import matplotlib.pyplot as plt
  2. Prepare the data (lists or arrays)
  3. Choose the chart type and call the appropriate function
  4. Customize with title, labels, colors, and grid
  5. Display with plt.show() or save with plt.savefig()

Mastering these basics opens the door to more advanced visualization libraries like Seaborn (built on top of Matplotlib), Plotly for interactive charts, and Pandas built-in plotting which also uses Matplotlib under the hood.

Leave a Comment

Your email address will not be published. Required fields are marked *