Fixed Top Ad (Local Preview)800x90 • Slot 6608427872
Matplotlib
✕1. Introduction to Matplotlib
- Matplotlib is a Python library used to create static visualizations. It supports common charts such as:
👉 Line charts
👉 Bar charts
👉 Scatter plots
👉 Histograms
👉 Box plots
👉 Pie charts
Install Matplotlib using:
pip install matplotlibImport it using:import matplotlib.pyplot as plt📌 Matplotlib helps us turn Python data into charts. - Matplotlib uses two important objects: Figure A Figure is the overall container or canvas. It can contain one or more plots. Axes An Axes is an individual plotting area inside the Figure. It contains: 👉 X-axis 👉 Y-axis 👉 Chart title 👉 Labels 👉 Data elements 📌 The Figure is like a page. 📌 Each Axes is a chart placed on that page.
- We commonly create a Figure and Axes using:
fig, ax = plt.subplots()plt.subplots()returns the enclosing Figure and either one Axes object or an array of Axes objects, depending on the requested subplot layout. Here:fig→ Figure objectax→ Axes object - Using the Axes, we can customize: 👉 Chart data 👉 Title 👉 Axis labels 👉 Axis limits 👉 Tick marks 👉 Grid 👉 Legend Using the Figure, we can customize: 👉 Overall size 👉 Layout 👉 Overall title 👉 Saving and exporting
1.1 📊 What is Matplotlib?
1.2 Figure and Axes
1.3 Creating a Figure and Axes
1.4 What Do We Customize?
2. Plotting Equations with Matplotlib
import numpy as npimport matplotlib.pyplot as plt# Create 50 values between 0 and 2πx = np.linspace(0, 2 * np.pi, 50)# Calculate function valuesy_sin = np.sin(x)y_cos = np.cos(x)# Create Figure and Axesfig, ax = plt.subplots()# Plot equationsax.plot(x, y_sin, label="sin(x)")ax.plot(x, y_cos, label="cos(x)")# Add chart informationax.set_title("Trigonometric Functions")ax.set_xlabel("Angle in Radians")ax.set_ylabel("Function Value")ax.legend()plt.show()ax.plot(x, y_sin, label="sin(x)")uses:xfor horizontal-axis valuesy_sinfor vertical-axis valueslabel="sin(x)"assigns a name that can be displayed by:ax.legend()📌 Create the data, create the Axes, plot the data, customize the chart, and show it.
2.1 📈 Plotting Sine and Cosine
2.2 Understanding the Code
3. Multiple Plots in One Figure
- Subplots allow us to place multiple charts inside one Figure.
Example:
fig, axes = plt.subplots(1, 2)This creates: - 1 row - 2 columns - 2 Axes objects With a 1 × 2 layout, Matplotlib returns a one-dimensional array of Axes objects, so we access them withaxes[0]andaxes[1]. import numpy as npimport matplotlib.pyplot as pltx = np.linspace(0, 2 * np.pi, 50)y_sin = np.sin(x)y_cos = np.cos(x)fig, axes = plt.subplots(1, 2, figsize=(10, 4))# First subplotaxes[0].plot(x, y_sin, color="blue")axes[0].set_title("Sine Function")axes[0].set_xlabel("Angle in Radians")axes[0].set_ylabel("sin(x)")# Second subplotaxes[1].plot(x, y_cos, color="orange")axes[1].set_title("Cosine Function")axes[1].set_xlabel("Angle in Radians")axes[1].set_ylabel("cos(x)")plt.tight_layout()plt.show()plt.tight_layout()adjusts spacing between subplots. It helps prevent chart elements such as titles and labels from overlapping. 📌 Subplots place multiple Axes inside one Figure.
3.1 🧩 What are Subplots?
3.2 Example: Sine and Cosine Subplots
3.3 What is tight_layout()?
4. Customizing Matplotlib Charts
- Add a Title
ax.set_title("Monthly Sales")Set X-Axis Labelax.set_xlabel("Month")Set Y-Axis Labelax.set_ylabel("Sales in NPR")Change Colorax.plot(x, y, color="red")Common color names include: blue, green, orange, purple, red ax.plot(x, y, linestyle="--")
4.1 🎨 Common Customization Options
4.2 Customize Line Style
Common Line Styles
| Style | Meaning |
|---|---|
| "-" | Solid |
| "--" | Dashed |
| ":" | Dotted |
| "-." | Dash-dot |
- A marker is a symbol used to show each individual data point on a line or plot.
Example
ax.plot(x, y, marker="o")Here, marker="o" displays a circle at each data point.
4.3 Customize Markers
Common Markers
| Marker | Shape |
|---|---|
| "o" | Circle |
| "s" | Square |
| "^" | Triangle |
| "*" | Star |
| "x" | Cross |
| "d" | Diamond |
ax.plot(x, y, linewidth=2)Larger values create thicker lines.ax.plot(x, y, alpha=0.5)Here:alpha=0→ fully transparentalpha=1→ fully visible- Set the X-axis range:
ax.set_xlim(0, 2 * np.pi)Set the Y-axis range:ax.set_ylim(-1, 1) ax.set_xticks([0,np.pi / 2,np.pi,3 * np.pi / 2,2 * np.pi])ax.set_xticklabels(["0","Ï€/2","Ï€","3Ï€/2","2Ï€"])ax.grid(True)ax.legend()The grid can help readers compare values with the axes. The legend explains the meaning of plotted lines, colors, or markers.- The borders surrounding an Axes are called spines.
Hide the top border:
ax.spines["top"].set_visible(False)Change border color:ax.spines["left"].set_color("gray")Change border thickness:ax.spines["left"].set_linewidth(2) fig.suptitle("Trigonometric Functions", fontsize=16)📌ax.set_title()adds a title to one Axes. 📌fig.suptitle()adds an overall title to the Figure.
4.4 Customize Line Thickness
4.5 Customize Transparency
4.6 Set Axis Limits
4.7 Customize Tick Marks and Labels
4.8 Add Grid and Legend
4.9 Customize Chart Borders
4.10 Add an Overall Figure Title
5. Bar Chart in Matplotlib
- A bar chart compares numeric values across categories.
Examples:
👉 Sales by product
👉 Revenue by region
👉 Students by course
Create a vertical bar chart using:
ax.bar()Create a horizontal bar chart using:ax.barh() import matplotlib.pyplot as pltproducts = ["Product A","Product B","Product C"]sales = [100, 200, 150]fig, ax = plt.subplots()sales_bars = ax.bar(products,sales,color=["red", "green", "blue"])ax.bar_label(sales_bars,label_type="center")ax.set_title("Sales by Product")ax.set_xlabel("Product")ax.set_ylabel("Sales")plt.show()fig, ax = plt.subplots()sales_bars = ax.barh(products, sales)ax.bar_label(sales_bars)ax.set_title("Sales by Product")ax.set_xlabel("Sales")ax.set_ylabel("Product")plt.show()📌 Inbarh(), categories are supplied first and numeric values second.
5.1 📊 What is a Bar Chart?
5.2 Vertical Bar Chart Example
5.3 Horizontal Bar Chart
6. Stacked Bar Chart
- A stacked bar chart shows: - The total value for each category - The contribution of subcategories to that total Example: - Gold and silver medals won by each country.
import numpy as npimport matplotlib.pyplot as pltcountries = ["Country A","Country B","Country C"]gold_medals = [10, 20, 15]silver_medals = [5, 10, 8]fig, ax = plt.subplots()silver_bars = ax.bar(countries,silver_medals,label="Silver")gold_bars = ax.bar(countries,gold_medals,bottom=silver_medals,label="Gold")ax.bar_label(silver_bars,label_type="center")ax.bar_label(gold_bars,label_type="center")ax.set_title("Medal Counts by Country")ax.set_xlabel("Country")ax.set_ylabel("Number of Medals")ax.legend()plt.show()📌 Thebottomparameter tells Matplotlib where the next set of bars should begin.
6.1 🧱 What is a Stacked Bar Chart?
6.2 Stacked Bar Chart Example
7. Pie and Donut Charts
- A pie chart shows how categories contribute to a whole. It is created using:
ax.pie()Pie charts work best with only a few categories. import matplotlib.pyplot as pltclubs = ["Man City","Man United","Liverpool","Chelsea"]titles = [9, 13, 1, 5]fig, ax = plt.subplots()ax.pie(titles,labels=clubs,autopct="%1.1f%%")ax.set_title("League Wins by Team")plt.show()autopctformats the percentage labels displayed on the chart.- A donut chart is a pie chart with space in the center.
fig, ax = plt.subplots()ax.pie(titles,labels=clubs,autopct="%1.1f%%",wedgeprops={"width": 0.6})ax.set_title("League Wins by Team")plt.show()📌 The width value controls the size of the donut ring.
7.1 🥧 What is a Pie Chart?
7.2 Pie Chart Example
7.3 Donut Chart Example
8. Histogram in Matplotlib
- A histogram shows the distribution of one numeric variable. It groups values into intervals called bins and displays the number of observations in each interval. It is created using:
ax.hist() import numpy as npimport matplotlib.pyplot as pltdata = np.random.randn(1000)fig, ax = plt.subplots()ax.hist(data,bins=30,color="skyblue",edgecolor="black")ax.set_title("Distribution of Random Values")ax.set_xlabel("Value")ax.set_ylabel("Frequency")plt.show()- The number of bins affects the appearance of the distribution. One simple guideline is:
bins ≈ √nwhere n is the number of observations. This is only a guideline. The appropriate number of bins depends on the data and the detail we want to show. - Create a cumulative histogram:
ax.hist(data, bins=30, cumulative=True)Create a density histogram:ax.hist(data, bins=30, density=True)📌cumulative=Trueshows accumulated frequency. 📌density=Truenormalizes the histogram so its total area equals one.
8.1 📶 What is a Histogram?
8.2 Histogram Example
8.3 Choosing the Number of Bins
8.4 Histogram Options
9. Box Plot in Matplotlib
- A box plot shows the distribution of numeric values. It displays: - Median - Quartiles - Overall spread - Potential outliers It is useful for comparing distributions across categories.
import numpy as npimport matplotlib.pyplot as pltdata = [np.random.randn(100) + ifor i in range(4)]fig, ax = plt.subplots()ax.boxplot(data,tick_labels=["Group 1","Group 2","Group 3","Group 4"])ax.set_title("Distribution by Group")ax.set_xlabel("Group")ax.set_ylabel("Value")plt.show()
9.1 📦 What is a Box Plot?
9.2 Box Plot Example
10. Scatter Plot in Matplotlib
- A scatter plot shows the relationship between two numeric variables. It can help reveal:
- Positive relationships
- Negative relationships
- Clusters
- Unusual observations
It is created using:
ax.scatter() import numpy as npimport matplotlib.pyplot as pltx = np.random.rand(100)y = np.random.rand(100)fig, ax = plt.subplots()ax.scatter(x,y,color="purple",alpha=0.5)ax.set_title("Relationship Between X and Y")ax.set_xlabel("X Value")ax.set_ylabel("Y Value")plt.show()- Customize marker shape:
ax.scatter(x, y, marker="x")Customize point size:ax.scatter(x, y, s=100)Customize color:ax.scatter(x, y, color="green")Customize transparency:ax.scatter(x, y, alpha=0.5)📌 Inscatter(), thesparameter controls marker size.
10.1 🔵 What is a Scatter Plot?
10.2 Scatter Plot Example
10.3 Customizing Scatter Points
11. Setting Styles in Matplotlib
- Matplotlib provides built-in style sheets that change the overall appearance of charts. Set a style using:
plt.style.use("style_name")
11.1 🎨 What are Matplotlib Styles?
11.2 Common Styles
| Style | General Appearance |
|---|---|
| ggplot | Style inspired by ggplot |
| bmh | Style designed for statistical visualizations |
| fivethirtyeight | Style inspired by data-journalism charts |
| dark_background | Dark background with light chart elements |
| grayscale | Grayscale appearance suitable for monochrome output |
| Solarize_Light2 | Light solarized color scheme |
| tableau-colorblind10 | Colorblind-friendly color cycle |
import matplotlib.pyplot as pltplt.style.use("ggplot")fig, ax = plt.subplots()ax.plot([1, 2, 3], [10, 20, 15])ax.set_title("Styled Line Chart")ax.set_xlabel("Period")ax.set_ylabel("Value")plt.show()📌 Set the style before creating the chart.
11.3 Style Example
12. Saving Plots
- Matplotlib can save figures in formats such as:
- PNG
- PDF
- SVG
- JPG
Use:
fig.savefig()Using the Figure object makes it clear which Figure is being saved. fig.savefig("plot.png",dpi=300,bbox_inches="tight")Here:"plot.png"is the filenamedpi=300controls resolutionbbox_inches="tight"reduces extra surrounding whitespacefig.savefig("plot.pdf",format="pdf",bbox_inches="tight")- Figure size is set when creating the Figure:
fig, axes = plt.subplots(2,2,figsize=(10, 6))The figsize values represent width and height in inches. Additional keywords supplied toplt.subplots()are passed to the Figure creation call, which is whyfigsizecan be set there. import matplotlib.pyplot as pltfig, ax = plt.subplots(figsize=(8, 5))ax.plot([1, 2, 3, 4],[10, 20, 15, 30])ax.set_title("Monthly Performance")ax.set_xlabel("Month")ax.set_ylabel("Value")fig.savefig("plot.png",dpi=300,bbox_inches="tight")plt.show()📌 Save the Figure before callingplt.show()to avoid backend-dependent behavior.
12.1 💾 Saving a Figure
12.2 Save as PNG
12.3 Save as PDF
12.4 Set Figure Size
12.5 Complete Saving Example
