Fixed Top Ad (Local Preview)800x90 • Slot 6608427872

Matplotlib

✕

1. Introduction to Matplotlib

    1.1 📊 What is Matplotlib?
    1. 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 matplotlib Import it using: import matplotlib.pyplot as plt 📌 Matplotlib helps us turn Python data into charts.
    1.2 Figure and Axes
    1. 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.
    1.3 Creating a Figure and Axes
    1. 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 object ax → Axes object
    1.4 What Do We Customize?
    1. 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

2. Plotting Equations with Matplotlib

    2.1 📈 Plotting Sine and Cosine
    1. import numpy as np import matplotlib.pyplot as plt# Create 50 values between 0 and 2Ï€ x = np.linspace(0, 2 * np.pi, 50)# Calculate function values y_sin = np.sin(x) y_cos = np.cos(x)# Create Figure and Axes fig, ax = plt.subplots()# Plot equations ax.plot(x, y_sin, label="sin(x)") ax.plot(x, y_cos, label="cos(x)")# Add chart information ax.set_title("Trigonometric Functions") ax.set_xlabel("Angle in Radians") ax.set_ylabel("Function Value") ax.legend()plt.show()
    2.2 Understanding the Code
    1. ax.plot(x, y_sin, label="sin(x)") uses: x for horizontal-axis values y_sin for vertical-axis values label="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.

3. Multiple Plots in One Figure

    3.1 🧩 What are Subplots?
    1. 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 with axes[0] and axes[1].
    3.2 Example: Sine and Cosine Subplots
    1. import numpy as np import 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 subplot axes[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 subplot axes[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()
    3.3 What is tight_layout()?
    1. 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.

4. Customizing Matplotlib Charts

    4.1 🎨 Common Customization Options
    1. Add a Title ax.set_title("Monthly Sales")Set X-Axis Label ax.set_xlabel("Month")Set Y-Axis Label ax.set_ylabel("Sales in NPR")Change Color ax.plot(x, y, color="red") Common color names include: blue, green, orange, purple, red
    4.2 Customize Line Style
    1. ax.plot(x, y, linestyle="--")
Common Line Styles
StyleMeaning
"-"Solid
"--"Dashed
":"Dotted
"-."Dash-dot
    4.3 Customize Markers
    1. A marker is a symbol used to show each individual data point on a line or plot. Exampleax.plot(x, y, marker="o") Here, marker="o" displays a circle at each data point.
Common Markers
MarkerShape
"o"Circle
"s"Square
"^"Triangle
"*"Star
"x"Cross
"d"Diamond
    4.4 Customize Line Thickness
    1. ax.plot(x, y, linewidth=2) Larger values create thicker lines.
    4.5 Customize Transparency
    1. ax.plot(x, y, alpha=0.5) Here: alpha=0 → fully transparent alpha=1 → fully visible
    4.6 Set Axis Limits
    1. Set the X-axis range: ax.set_xlim(0, 2 * np.pi) Set the Y-axis range: ax.set_ylim(-1, 1)
    4.7 Customize Tick Marks and Labels
    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Ï€" ])
    4.8 Add Grid and Legend
    1. 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.
    4.9 Customize Chart Borders
    1. 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)
    4.10 Add an Overall Figure Title
    1. fig.suptitle("Trigonometric Functions", fontsize=16) 📌 ax.set_title() adds a title to one Axes. 📌 fig.suptitle() adds an overall title to the Figure.

5. Bar Chart in Matplotlib

    5.1 📊 What is a Bar Chart?
    1. 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()
    5.2 Vertical Bar Chart Example
    1. 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()
    5.3 Horizontal Bar Chart
    1. 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() 📌 In barh(), categories are supplied first and numeric values second.

6. Stacked Bar Chart

    6.1 🧱 What is a Stacked Bar Chart?
    1. 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.
    6.2 Stacked Bar Chart Example
    1. import numpy as np import 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() 📌 The bottom parameter tells Matplotlib where the next set of bars should begin.

7. Pie and Donut Charts

    7.1 🥧 What is a Pie Chart?
    1. 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.
    7.2 Pie Chart Example
    1. 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()autopct formats the percentage labels displayed on the chart.
    7.3 Donut Chart Example
    1. 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.

8. Histogram in Matplotlib

    8.1 📶 What is a Histogram?
    1. 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()
    8.2 Histogram Example
    1. import numpy as np import 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()
    8.3 Choosing the Number of Bins
    1. The number of bins affects the appearance of the distribution. One simple guideline is: bins ≈ √n where 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.
    8.4 Histogram Options
    1. Create a cumulative histogram: ax.hist(data, bins=30, cumulative=True) Create a density histogram: ax.hist(data, bins=30, density=True) 📌 cumulative=True shows accumulated frequency. 📌 density=True normalizes the histogram so its total area equals one.

9. Box Plot in Matplotlib

    9.1 📦 What is a Box Plot?
    1. 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.
    9.2 Box Plot Example
    1. import numpy as np import 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()

10. Scatter Plot in Matplotlib

    10.1 🔵 What is a Scatter Plot?
    1. 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()
    10.2 Scatter Plot Example
    1. import numpy as np import 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()
    10.3 Customizing Scatter Points
    1. 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) 📌 In scatter(), the s parameter controls marker size.

11. Setting Styles in Matplotlib

    11.1 🎨 What are Matplotlib Styles?
    1. Matplotlib provides built-in style sheets that change the overall appearance of charts. Set a style using: plt.style.use("style_name")
11.2 Common Styles
StyleGeneral Appearance
ggplotStyle inspired by ggplot
bmhStyle designed for statistical visualizations
fivethirtyeightStyle inspired by data-journalism charts
dark_backgroundDark background with light chart elements
grayscaleGrayscale appearance suitable for monochrome output
Solarize_Light2Light solarized color scheme
tableau-colorblind10Colorblind-friendly color cycle
    11.3 Style Example
    1. 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.

12. Saving Plots

    12.1 💾 Saving a Figure
    1. 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.
    12.2 Save as PNG
    1. fig.savefig("plot.png",dpi=300,bbox_inches="tight" ) Here: "plot.png" is the filename dpi=300 controls resolution bbox_inches="tight" reduces extra surrounding whitespace
    12.3 Save as PDF
    1. fig.savefig("plot.pdf",format="pdf",bbox_inches="tight" )
    12.4 Set Figure Size
    1. 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 to plt.subplots() are passed to the Figure creation call, which is why figsize can be set there.
    12.5 Complete Saving Example
    1. 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 calling plt.show() to avoid backend-dependent behavior.
Ad PlaceholderSlot: 7421026683

Practice QuestionsNot started

  1. WIP

    Question 1 of 1

    • WIP
Ad PlaceholderSlot: 5413242224