Matplotlib

Introduction to Matplotlib

  • External library for creating static visualizations in Python.
  • Installed as: pip install matplotlib.
  • Has axis and figure objects for flexible plotting. - axis: Represents a single plot area with x and y axes. - figure: Container for one or more axes (plots).
  • Supports Charts like: line, bar, scatter, histogram, pie etc.
  • figure and axis objects is created with plt.subplots()
  • Using axis, we can customize titles, labels, grid, legends etc.
  • Using figure, we can customize size, layout, save etc.

Plotting equations with Matplotlib

  • import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 50) # 50 points from 0 to 2π y1 = np.sin(x) # Equation to plot y2 = np.cos(x) fig, ax = plt.subplots() ax.plot(x, y1, label="sin(x)") ax.plot(x, y2, label="cos(x)") ax.set_title("Trigonometric Functions") ax.set_xlabel("Angle (radians)") ax.set_ylabel("Function Value") ax.legend() plt.show()

Multiple plots in one figure

  • plt.subplots(1, 2) creates a figure with 1 rows and 2 columns.
  • We can plot different equations in each subplot.
  • Example: fig, ax = plt.subplots(1, 2) x = np.linspace(0, 2 * np.pi, 50) y_sin = np.sin(x) y_cos = np.cos(x) # First subplot ax[0].plot(x, y_sin, label="sin(x)", color="blue") ax[0].set_title("Sine Function") ax[0].set_xlabel("Angle (radians)") ax[0].set_ylabel("sin(x)") # Second subplot ax[1].plot(x, y_cos, label="cos(x)", color="orange") ax[1].set_title("Cosine Function") ax[1].set_xlabel("Angle (radians)") ax[1].set_ylabel("cos(x)") plt.tight_layout() plt.show()

Customizing Matplotlib Charts

Common Customization Options:
DescriptionExample
Adding Title to plotax.set_title("Title")
Customizing Colorax.plot(x, y, color="red") # Other options: blue, green, orange, purple etc.
Customizing Line Styleax.plot(x, y, linestyle="--") # Dash line. Other options: -, :, -.
Customizing Marker Styleax.plot(x, y, marker="o") # Circle marker. Other options: s, ^, *, x, d etc.
Setting Label on X-axisax.set_xlabel("X-axis Label", color="green", fontsize=12)
Setting Label on Y-axisax.set_ylabel("Y-axis Label", color="blue", fontsize=12)
Limiting X-axis Rangesax.set_xlim(0, 2*np.pi)
Customizing Tick Marksax.set_xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
Customizing Tick Labelsax.set_xticklabels(["0", "π/2", "π", "3π/2", "2π"])
Limiting Y-axis Rangesax.set_ylim(-1, 1)
Customizing Thicknessax.plot(x, y, linewidth=2)
Setting Gridax.grid(True)
Adding Legendax.legend()
Customizing Transparencyax.plot(x, y, alpha=0.5) # 0.5 => 50% transparent.
Border Customizationax.spines["top"].set_visible(False) # .set_color(), .set_linewidth()
Setting Overall Titlefig.suptitle("Overall Title", fontsize=16)
Common customization options in Matplotlib to enhance the appearance and readability

Barplot in Matplotlib

  • Used to compare values across categories. i.e category vs numeric
  • Created with ax.bar() or ax.barh().
  • Example:products = ["Product A", "Product B", "Product C"] sales = [100, 200, 150] fig, ax = plt.subplots() sales_bar = ax.bar(products, sales, color=["red", "green", "blue"]) # ax.barh(sales, products) # For horizontal bar plot ax.bar_label(sales_bar, label_type='center') ax.set_title("Bar Plot Example") ax.set_xlabel("Category") ax.set_ylabel("Sales") plt.show()

Stacked Barplot in Matplotlib

  • Used to show composition of categories with sub-categories.
  • Created by stacking bars on top or right of other.
  • Example: import numpy as np import matplotlib.pyplot as plt countries = ["Country A", "Country B", "Country C"] gold_mdl = [10, 20, 15] silver_mdl = [5, 10, 8] fig, ax = plt.subplots() silver_plt = ax.bar(countries, silver_mdl, label="Silver") gold_plt = ax.bar(countries, gold_mdl, bottom=silver_mdl, label="Gold") ax.bar_label(gold_plt, label_type='center') ax.bar_label(silver_plt, label_type='center') ax.set_title("Medal Counts by Country") ax.set_xlabel("Country") ax.set_ylabel("Medals") ax.legend() plt.show()

Pie Chart and Donut Chart in Matplotlib

  • Used to show parts of a whole. category vs numeric.
  • Created with ax.pie().
  • Example: clubs = ["Man City", "Man United", "Liverpool", "Chelsea"] titles = [9, 13, 1, 5] fig, ax = plt.subplots() ax.pie(titles, labels=clubs, autopct="%1.1f%%") plt.show() # For donut chart ax.pie(titles, labels=clubs, autopct="%1.1f%%", wedgeprops={"width": 0.6}) ax.set_title("League Wins by Each Team") plt.show()

Plotting Histogram in Matplotlib

  • Used to show distribution of a single continuous variable.
  • Shows frequency of data points in specified ranges (bins).
  • Created with ax.hist(). bins = √n shows proper distribution.
  • cumulative=True => cumulative distribution, density=True => pdf.
  • Example: import numpy as np import matplotlib.pyplot as plt data = np.random.randn(1000) fig, ax = plt.subplots() ax.hist(data, bins=30, color="skyblue", edgecolor="black") ax.set_title("Histogram Example") ax.set_xlabel("Value") ax.set_ylabel("Frequency") plt.show()

Box Plot in Matplotlib

  • To show distribution & outliers of a continuous variable across categories.
  • Displays median, quartiles, and potential outliers.
  • Created with ax.boxplot().
  • Example: import numpy as np import matplotlib.pyplot as plt data = [np.random.randn(100) + i for i in range(4)] fig, ax = plt.subplots() ax.boxplot(data, tick_labels=["Group 1", "Group 2", "Group 3", "Group 4"]) ax.set_title("Box Plot Example") ax.set_xlabel("Group") ax.set_ylabel("Value") plt.show()

Scatter Plot in Matplotlib

  • Used to show relationship between two continuous variables.
  • Created with ax.scatter().
  • marker, size, color can be customized as per requirement.
  • Example: import numpy as np import matplotlib.pyplot as plt x = 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("Scatter Plot Example") ax.set_xlabel("X-axis") ax.set_ylabel("Y-axis") plt.show()

Setting Styles in Matplotlib

  • Matplotlib has built-in styles to improve aesthetics.
  • Set style with plt.style.use("style_name").
Popular Matplotlib Styles:
Style NameUse Case
ggplotInspired by R's ggplot2. Good for publication-quality plots.
bmhBayesian Methods for Hackers style. Good for statistical plots.
fivethirtyeightGood for data journalism.
dark_backgroundDark background with bright colors. Good for presentations.
grayscaleGrayscale style. Good for print media.
Solarize_Light2Solarized light color scheme. Good for readability.
tableau-colorblind10Colorblind-friendly palette.
Popular Matplotlib styles and their descriptions

Saving Plots in Matplotlib

  • Use plt.savefig() to save plots in various formats.
  • Specify resolution with dpi parameter.
  • Control layout with bbox_inches. "tight" removes extra whitespace.
  • Format can be controlled with format. Values: png, pdf, svg, jpg etc.
  • Figure size can be set with figsize in plt.subplots(). Values are in inches.
  • Example: fig, ax = plt.subplots(2, 2, figsize=(10, 6)) plt.savefig("plot.png", dpi=300, bbox_inches="tight") plt.savefig("plot.pdf", format="pdf", bbox_inches="tight")