{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \ud83c\udfcb\ufe0f Matplotlib Practice Exercise 1: Core Fundamentals & Practical Operations\n", "\n", "This notebook contains **20 progressive, practical problems** designed to build confidence and muscle memory with Matplotlib:\n", "- The Object-Oriented paradigm (`fig, ax = plt.subplots()`)\n", "- Line plots, markers, linestyles, and shaded confidence intervals\n", "- Multi-dimensional scatter plots, continuous colormaps, and colorbars\n", "- Vertical, horizontal, grouped, and stacked bar charts with direct labels\n", "- Histograms, probability densities, and cumulative distributions\n", "- Statistical spreads with box plots and violin plots\n", "- Multi-panel subplot grids (1D and 2D) and twin axes\n", "- Publication typography, LaTeX formulas, clean spines, and figure export\n", "\n", "---\n", "*Tip: Complete solutions are available in `03_matplotlib_exercise_1_solutions.ipynb`.*\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 1: Import Matplotlib and Check Version\n", "\n", "Import `matplotlib as mpl`, `matplotlib.pyplot as plt`, and `numpy as np`. Print their installed version numbers.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib as mpl\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "# Print installed versions below\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 2: Basic Object-Oriented Line Plot\n", "\n", "Create a 1D array `x` with 100 points from 0 to $2\\pi$. Compute $y = \\sin(x)$.\n", "Using the Object-Oriented interface (`plt.subplots()`), plot $y$ vs $x$ with:\n", "- Figure size `(8, 4)` and DPI 100\n", "- Blue solid line with `linewidth=2`\n", "- Title: `'Sine Function'`\n", "- X-axis label: `'x (radians)'`\n", "- Y-axis label: `'sin(x)'`\n", "- Grid enabled with dashed lines and 0.5 alpha\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create data and plot below\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3: Multiple Lines with Custom Linestyles & Legend\n", "\n", "On a single Axes, plot three curves over $x \\in [0, 10]$:\n", "1. $y_1 = \\sin(x)$: Solid line (`'-'`), color `'#2b5c8f'`, label `'sin(x)'`\n", "2. $y_2 = \\cos(x)$: Dashed line (`'--'`), color `'#e27d60'`, label `'cos(x)'`\n", "3. $y_3 = \\sin(x) \\cdot e^{-0.2x}$: Dotted line (`':'`), color `'#2ca02c'`, linewidth 2.2, label `'Damped'`\n", "Add an axis title, legend with frame at upper right, and grid.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create and plot 3 curves below\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 4: Line Plot with Custom Markers\n", "\n", "Given the weekly sensor temperatures:\n", "`days = np.arange(1, 8)`\n", "`temps = np.array([21.2, 23.5, 22.0, 25.8, 26.4, 24.1, 23.0])`\n", "Plot a line chart where:\n", "- Line color is black (`'#222222'`), linewidth=1.8\n", "- Markers are diamonds (`marker='D'`), `markersize=7`\n", "- Marker fill color is white (`markerfacecolor='white'`)\n", "- Marker outline is red (`markeredgecolor='red'`) with `markeredgewidth=1.5`\n", "Set X-ticks to exactly the 7 days.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "days = np.arange(1, 8)\n", "temps = np.array([21.2, 23.5, 22.0, 25.8, 26.4, 24.1, 23.0])\n", "\n", "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 5: Shaded Uncertainty Band (`fill_between`)\n", "\n", "Simulate an experimental process:\n", "- $t \\in [0, 10]$ with 100 points\n", "- Mean trajectory: $\\mu(t) = 10 + 2t - 0.15 t^2$\n", "- Uncertainty: $\\sigma(t) = 0.5 + 0.1t$\n", "Plot the mean curve in navy, and shade the $\\mu \\pm 1.5\\sigma$ band using `ax.fill_between()` with `alpha=0.25`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 6: 2D Scatter Plot with Proportional Marker Sizes (Bubble Chart)\n", "\n", "Generate 60 random points:\n", "- `x`: uniform in $[10, 100]$\n", "- `y`: $1.2x + \\mathcal{N}(0, 15)$\n", "- `sizes`: uniform in $[30, 300]$ points$^2$\n", "Plot a scatter chart where marker area equals `sizes`, `color='#2b5c8f'`, `alpha=0.6`, with black edge color.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 7: Continuous Colormap Scatter & Colorbar\n", "\n", "Using the data from Problem 6, map a continuous fourth variable `z = x + 0.8 * y` to the marker color using `cmap='plasma'`.\n", "Attach a labeled colorbar on the right with label `'Magnitude Z'`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 8: Categorical Scatter with Horizontal Jitter\n", "\n", "Given three customer tiers with 50 satisfaction scores each:\n", "- Bronze: $\\mathcal{N}(65, 8)$\n", "- Silver: $\\mathcal{N}(78, 6)$\n", "- Gold: $\\mathcal{N}(89, 5)$\n", "Plot the observations on categorical X-axis positions (0, 1, 2). Apply horizontal jitter $\\mathcal{U}(-0.12, 0.12)$ to each point so points do not stack directly on top of each other.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 9: Vertical Bar Chart with Direct Value Labels\n", "\n", "Given departmental revenues (in thousands of dollars):\n", "`depts = ['Engineering', 'Marketing', 'Sales', 'Finance', 'Support']`\n", "`revenues = [420, 280, 590, 310, 190]`\n", "Create a vertical bar chart with:\n", "- Navy bars with black outlines\n", "- Direct value labels stamped on each bar using `ax.bar_label()` formatted as `\"$%dK\"` with 3pt padding\n", "- Y-axis upper limit adjusted to accommodate labels cleanly\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "depts = ['Engineering', 'Marketing', 'Sales', 'Finance', 'Support']\n", "revenues = [420, 280, 590, 310, 190]\n", "\n", "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 10: Horizontal Bar Chart with Inverted Y-Axis\n", "\n", "Given model names and F1 scores:\n", "`models = ['DecisionTree', 'kNN', 'NaiveBayes', 'LogisticReg', 'RandomForest', 'XGBoost']`\n", "`f1_scores = [0.72, 0.78, 0.75, 0.83, 0.91, 0.94]`\n", "Sort the models by score ascending, create a horizontal bar chart (`ax.barh`), invert the Y-axis so the highest performer is at the top, and label bars with `ax.bar_label()`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "models = ['DecisionTree', 'kNN', 'NaiveBayes', 'LogisticReg', 'RandomForest', 'XGBoost']\n", "f1_scores = [0.72, 0.78, 0.75, 0.83, 0.91, 0.94]\n", "\n", "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 11: Grouped Bar Chart with Coordinate Offsets\n", "\n", "Given quarterly metrics for Product A and Product B across 4 quarters:\n", "- `quarters = ['Q1', 'Q2', 'Q3', 'Q4']`\n", "- `prod_a = [120, 150, 170, 190]`\n", "- `prod_b = [95, 130, 185, 210]`\n", "Plot a grouped bar chart with `bar_width = 0.35` placing bars side-by-side using $x \\pm \\text{width}/2$ offsets. Include a legend.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "quarters = ['Q1', 'Q2', 'Q3', 'Q4']\n", "prod_a = [120, 150, 170, 190]\n", "prod_b = [95, 130, 185, 210]\n", "\n", "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 12: Stacked Bar Chart\n", "\n", "Using the data from Problem 11, create a stacked bar chart where Product B sits directly on top of Product A using the `bottom` parameter. Add a legend and title.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 13: Normalized Histogram with Automated Binning\n", "\n", "Generate 1,500 samples from a normal distribution $\\mathcal{N}(50, 10)$.\n", "Plot a normalized histogram with `density=True` and `bins='auto'`.\n", "Overlay the theoretical Gaussian PDF curve $f(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}$ in red.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 14: Overlapping Histograms with Stepped Outlines\n", "\n", "Generate two distributions:\n", "- Group 1: $\\mathcal{N}(100, 15)$, 1,000 samples\n", "- Group 2: $\\mathcal{N}(115, 12)$, 1,000 samples\n", "Plot both on the same axes using `density=True`, `alpha=0.35` for fill, and `histtype='step'` for crisp outlines.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 15: Box Plot with Custom Patch Colors & Notches\n", "\n", "Generate four datasets with 100 samples each:\n", "- D1: $\\mathcal{N}(20, 3)$\n", "- D2: $\\mathcal{N}(25, 4)$\n", "- D3: $\\mathcal{N}(22, 6)$\n", "- D4: $\\mathcal{N}(30, 2)$\n", "Create a boxplot with `patch_artist=True`, `notch=True`, custom box face colors, and labeled categories `['A', 'B', 'C', 'D']`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 16: Violin Plot with Medians and Extrema\n", "\n", "Using the same datasets D1, D2, D3 from Problem 15, plot a violin plot using `ax.violinplot()` with `showmeans=False` and `showmedians=True`. Set category tick labels to `['A', 'B', 'C']`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 17: Multi-Panel 2x2 Grid with Flattening\n", "\n", "Create a 2x2 grid of subplots using `plt.subplots(2, 2, figsize=(9, 6), layout='constrained')`.\n", "Iterate over `axs.flatten()` to plot:\n", "- Subplot 0: $x^2$\n", "- Subplot 1: $x^3$\n", "- Subplot 2: $\\sqrt{x}$\n", "- Subplot 3: $e^x$\n", "Over $x \\in [0, 4]$. Set unique titles and grid on each.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 18: Dual Y-Axes with `twinx()`\n", "\n", "Plot a 30-day timeline:\n", "- Left Y-axis (blue): Server CPU Load (%) ranging from 30% to 90%\n", "- Right Y-axis (orange): Active User Connections ranging from 1,000 to 5,000\n", "Combine legends from both axes into a single legend box in the upper-left.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 19: Logarithmic Scaling and Spine Removal\n", "\n", "Given $x \\in [1, 10]$ and $y = 10^x$:\n", "- Plot $y$ vs $x$ with logarithmic Y-axis scale (`ax.set_yscale('log')`)\n", "- Remove top and right spines using `ax.spines[['top', 'right']].set_visible(False)`\n", "- Offset left and bottom spines outward by 6 points using `.set_position(('outward', 6))`\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 20: High-Resolution Publication Figure Export\n", "\n", "Create a clean plot of $y = \\cos(x) e^{-x/5}$ over $x \\in [0, 15]$.\n", "Save the figure to disk as `'publication_plot.png'` with `dpi=300`, `bbox_inches='tight'`, and `facecolor='white'`.\n", "Verify the file exists, print its size in KB, and delete it to clean up.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.13.11" } }, "nbformat": 4, "nbformat_minor": 2 }