{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \ud83d\udca1 Matplotlib Practice Exercise 1: Solutions & Walkthroughs\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": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matplotlib version: 3.10.1\n", "NumPy version: 2.2.3\n" ] } ], "source": [ "import matplotlib as mpl\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "print(f\"Matplotlib version: {mpl.__version__}\")\n", "print(f\"NumPy version: {np.__version__}\")\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": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Blue sine wave on [0, 2*pi] with grid and labels\n" ] } ], "source": [ "x = np.linspace(0, 2 * np.pi, 100)\n", "y = np.sin(x)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n", "ax.plot(x, y, color='#1f77b4', linewidth=2, label=r'$\\sin(x)$')\n", "ax.set_title('Sine Function', fontsize=12, fontweight='bold')\n", "ax.set_xlabel('x (radians)')\n", "ax.set_ylabel('sin(x)')\n", "ax.grid(True, linestyle='--', alpha=0.5)\n", "ax.legend()\n", "plt.show()\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": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: 3 curves with distinct linestyles and legend\n" ] } ], "source": [ "x = np.linspace(0, 10, 150)\n", "y1 = np.sin(x)\n", "y2 = np.cos(x)\n", "y3 = np.sin(x) * np.exp(-0.2 * x)\n", "\n", "fig, ax = plt.subplots(figsize=(9, 4.5), dpi=100)\n", "ax.plot(x, y1, linestyle='-', color='#2b5c8f', linewidth=2, label=r'$\\sin(x)$')\n", "ax.plot(x, y2, linestyle='--', color='#e27d60', linewidth=2, label=r'$\\cos(x)$')\n", "ax.plot(x, y3, linestyle=':', color='#2ca02c', linewidth=2.2, label='Damped')\n", "\n", "ax.set_title('Trigonometric Waveforms & Damped Oscillator', fontweight='bold')\n", "ax.set_xlabel('Time (t)')\n", "ax.set_ylabel('Amplitude')\n", "ax.grid(True, linestyle=':', alpha=0.6)\n", "ax.legend(loc='upper right', frameon=True)\n", "plt.show()\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": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Temperature curve with red-bordered white diamond markers\n" ] } ], "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", "fig, ax = plt.subplots(figsize=(8, 4), dpi=100)\n", "ax.plot(days, temps, color='#222222', linewidth=1.8,\n", " marker='D', markersize=7, markerfacecolor='white', markeredgecolor='red', markeredgewidth=1.5)\n", "ax.set_title('Weekly Sensor Temperatures with Styled Diamond Markers', fontweight='bold')\n", "ax.set_xlabel('Day')\n", "ax.set_ylabel('Temperature (\u00b0C)')\n", "ax.set_xticks(days)\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "plt.show()\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": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Mean trajectory line with light-blue shaded uncertainty envelope\n" ] } ], "source": [ "t = np.linspace(0, 10, 100)\n", "mu = 10 + 2 * t - 0.15 * t**2\n", "sigma = 0.5 + 0.1 * t\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "ax.plot(t, mu, color='#1f77b4', linewidth=2.2, label=r'Mean Trajectory $\\mu(t)$')\n", "ax.fill_between(t, mu - 1.5 * sigma, mu + 1.5 * sigma, color='#1f77b4', alpha=0.25,\n", " label=r'Uncertainty Band ($\\mu \\pm 1.5\\sigma$)')\n", "ax.set_title('Process Trajectory with Shaded Uncertainty Band', fontweight='bold')\n", "ax.set_xlabel('Time (s)')\n", "ax.set_ylabel('Process Metric')\n", "ax.grid(True, linestyle=':', alpha=0.6)\n", "ax.legend(loc='upper left')\n", "plt.show()\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": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Bubble scatter plot with variable marker sizes\n" ] } ], "source": [ "rng = np.random.default_rng(42)\n", "x = rng.uniform(10, 100, 60)\n", "y = 1.2 * x + rng.normal(0, 15, 60)\n", "sizes = rng.uniform(30, 300, 60)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 5), dpi=100)\n", "ax.scatter(x, y, s=sizes, color='#2b5c8f', alpha=0.6, edgecolors='black', linewidths=0.7)\n", "ax.set_title('Bubble Chart: Marker Size Encodes 3rd Variable', fontweight='bold')\n", "ax.set_xlabel('Independent Variable X')\n", "ax.set_ylabel('Dependent Variable Y')\n", "ax.grid(True, linestyle='--', alpha=0.5)\n", "plt.show()\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": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Scatter dots colored by plasma gradient with right colorbar\n" ] } ], "source": [ "z = x + 0.8 * y\n", "fig, ax = plt.subplots(figsize=(8, 5), dpi=100)\n", "sc = ax.scatter(x, y, s=sizes, c=z, cmap='plasma', alpha=0.8, edgecolors='black', linewidths=0.5)\n", "cbar = fig.colorbar(sc, ax=ax, pad=0.03)\n", "cbar.set_label('Magnitude Z', fontweight='semibold')\n", "ax.set_title('Multi-Dimensional Scatter with Continuous Colormap', fontweight='bold')\n", "ax.set_xlabel('Variable X')\n", "ax.set_ylabel('Variable Y')\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "plt.show()\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": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Jittered observations for Bronze, Silver, and Gold tiers\n" ] } ], "source": [ "rng = np.random.default_rng(101)\n", "scores = [\n", " rng.normal(65, 8, 50),\n", " rng.normal(78, 6, 50),\n", " rng.normal(89, 5, 50)\n", "]\n", "tiers = ['Bronze', 'Silver', 'Gold']\n", "colors = ['#cd7f32', '#c0c0c0', '#ffd700']\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "for i, group in enumerate(scores):\n", " jitter = rng.uniform(-0.12, 0.12, len(group))\n", " ax.scatter(i + jitter, group, color=colors[i], edgecolors='black', alpha=0.7, s=35, label=tiers[i])\n", "\n", "ax.set_xticks([0, 1, 2])\n", "ax.set_xticklabels(tiers, fontweight='bold')\n", "ax.set_title('Customer Satisfaction by Tier (Horizontal Jitter Applied)', fontweight='bold')\n", "ax.set_ylabel('Satisfaction Score (0-100)')\n", "ax.grid(axis='y', linestyle=':', alpha=0.6)\n", "plt.show()\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": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Vertical bar chart with formatted currency value labels\n" ] } ], "source": [ "depts = ['Engineering', 'Marketing', 'Sales', 'Finance', 'Support']\n", "revenues = [420, 280, 590, 310, 190]\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "bars = ax.bar(depts, revenues, color='#2b5c8f', edgecolor='black', width=0.55)\n", "ax.bar_label(bars, fmt='$%dK', padding=3, fontweight='bold', fontsize=9)\n", "ax.set_ylim(0, 680)\n", "ax.set_title('Departmental Revenue Distribution', fontweight='bold', pad=12)\n", "ax.set_ylabel('Revenue ($k USD)')\n", "ax.grid(axis='y', linestyle=':', alpha=0.5)\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\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": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Horizontal bar chart sorted by F1 score with top model on top\n" ] } ], "source": [ "models = np.array(['DecisionTree', 'kNN', 'NaiveBayes', 'LogisticReg', 'RandomForest', 'XGBoost'])\n", "f1_scores = np.array([0.72, 0.78, 0.75, 0.83, 0.91, 0.94])\n", "\n", "sorted_idx = np.argsort(f1_scores)\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "bars = ax.barh(models[sorted_idx], f1_scores[sorted_idx], color='#41b3a3', edgecolor='black', height=0.55)\n", "ax.bar_label(bars, fmt='%.2f', padding=4, fontweight='bold', fontsize=9)\n", "ax.invert_yaxis()\n", "ax.set_xlim(0, 1.08)\n", "ax.set_title('Classifier Performance (Sorted F1 Score)', fontweight='bold')\n", "ax.set_xlabel('F1 Score')\n", "ax.grid(axis='x', linestyle=':', alpha=0.5)\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\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": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Grouped side-by-side bars for Products A and B\n" ] } ], "source": [ "quarters = ['Q1', 'Q2', 'Q3', 'Q4']\n", "prod_a = np.array([120, 150, 170, 190])\n", "prod_b = np.array([95, 130, 185, 210])\n", "x = np.arange(len(quarters))\n", "width = 0.35\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "ax.bar(x - width/2, prod_a, width, label='Product A', color='#2b5c8f', edgecolor='black')\n", "ax.bar(x + width/2, prod_b, width, label='Product B', color='#e27d60', edgecolor='black')\n", "ax.set_xticks(x)\n", "ax.set_xticklabels(quarters, fontweight='semibold')\n", "ax.set_ylabel('Units Sold (k)')\n", "ax.set_title('Quarterly Sales: Product A vs Product B', fontweight='bold')\n", "ax.legend(frameon=True)\n", "ax.grid(axis='y', linestyle=':', alpha=0.5)\n", "plt.show()\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": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Stacked vertical bar chart showing total combined sales\n" ] } ], "source": [ "fig, ax = plt.subplots(figsize=(7, 4.5), dpi=100)\n", "ax.bar(quarters, prod_a, width=0.45, label='Product A', color='#2b5c8f', edgecolor='black')\n", "ax.bar(quarters, prod_b, width=0.45, bottom=prod_a, label='Product B', color='#e27d60', edgecolor='black')\n", "ax.set_title('Cumulative Quarterly Sales (Stacked View)', fontweight='bold')\n", "ax.set_ylabel('Total Units Sold (k)')\n", "ax.legend(frameon=True)\n", "ax.grid(axis='y', linestyle=':', alpha=0.5)\n", "plt.show()\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": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Normalized histogram overlaid with theoretical Gaussian bell curve\n" ] } ], "source": [ "rng = np.random.default_rng(42)\n", "samples = rng.normal(50, 10, 1500)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "count, bins, _ = ax.hist(samples, bins='auto', density=True, color='#2b5c8f', alpha=0.6, edgecolor='white', label='Empirical Histogram')\n", "\n", "x_grid = np.linspace(15, 85, 200)\n", "pdf = (1 / (10 * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((x_grid - 50) / 10)**2)\n", "ax.plot(x_grid, pdf, color='red', linewidth=2.2, label='Theoretical PDF')\n", "\n", "ax.set_title('Normalized Histogram vs. Theoretical Normal PDF', fontweight='bold')\n", "ax.set_xlabel('Value')\n", "ax.set_ylabel('Probability Density')\n", "ax.legend(frameon=True)\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "plt.show()\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": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Two overlapping transparent distributions with sharp step outlines\n" ] } ], "source": [ "g1 = rng.normal(100, 15, 1000)\n", "g2 = rng.normal(115, 12, 1000)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "ax.hist(g1, bins=30, density=True, alpha=0.35, color='#1f77b4', label='Group 1')\n", "ax.hist(g1, bins=30, density=True, histtype='step', color='#1f77b4', lw=2)\n", "ax.hist(g2, bins=30, density=True, alpha=0.35, color='#d95f02', label='Group 2')\n", "ax.hist(g2, bins=30, density=True, histtype='step', color='#d95f02', lw=2)\n", "\n", "ax.set_title('Overlapping Density Distributions with Stepped Borders', fontweight='bold')\n", "ax.set_xlabel('Score')\n", "ax.set_ylabel('Density')\n", "ax.legend(frameon=True)\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "plt.show()\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": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: 4 colored notched box plots showing medians and IQRs\n" ] } ], "source": [ "d1 = rng.normal(20, 3, 100)\n", "d2 = rng.normal(25, 4, 100)\n", "d3 = rng.normal(22, 6, 100)\n", "d4 = rng.normal(30, 2, 100)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "bp = ax.boxplot([d1, d2, d3, d4], tick_labels=['A', 'B', 'C', 'D'], patch_artist=True, notch=True,\n", " medianprops=dict(color='white', lw=2))\n", "palette = ['#4575b4', '#74add1', '#fdae61', '#f46d43']\n", "for patch, color in zip(bp['boxes'], palette):\n", " patch.set_facecolor(color)\n", " patch.set_alpha(0.8)\n", "\n", "ax.set_title('Notched Box Plots across 4 Experimental Treatments', fontweight='bold')\n", "ax.set_ylabel('Observed Yield')\n", "ax.grid(axis='y', linestyle=':', alpha=0.5)\n", "plt.show()\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": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Violin plot displaying continuous probability density violins\n" ] } ], "source": [ "fig, ax = plt.subplots(figsize=(7, 4.5), dpi=100)\n", "vp = ax.violinplot([d1, d2, d3], positions=[1, 2, 3], showmeans=False, showmedians=True, showextrema=True)\n", "ax.set_xticks([1, 2, 3])\n", "ax.set_xticklabels(['A', 'B', 'C'], fontweight='bold')\n", "ax.set_title('Violin Plot: Kernel Density Probability Distributions', fontweight='bold')\n", "ax.set_ylabel('Observed Yield')\n", "ax.grid(axis='y', linestyle=':', alpha=0.5)\n", "plt.show()\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": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: 2x2 multi-panel grid displaying 4 distinct mathematical functions\n" ] } ], "source": [ "x_vals = np.linspace(0, 4, 100)\n", "funcs = [\n", " (x_vals**2, r'$y = x^2$', '#1f77b4'),\n", " (x_vals**3, r'$y = x^3$', '#ff7f0e'),\n", " (np.sqrt(x_vals), r'$y = \\sqrt{x}$', '#2ca02c'),\n", " (np.exp(x_vals), r'$y = e^x$', '#d62728')\n", "]\n", "\n", "fig, axs = plt.subplots(2, 2, figsize=(9, 6), dpi=100, layout='constrained')\n", "for ax, (y_data, title, col) in zip(axs.flatten(), funcs):\n", " ax.plot(x_vals, y_data, color=col, lw=2)\n", " ax.set_title(title, fontweight='bold')\n", " ax.grid(True, linestyle=':', alpha=0.5)\n", "fig.suptitle('Mathematical Functions in a 2x2 Multi-Panel Grid', fontsize=13, fontweight='bold')\n", "plt.show()\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": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Dual Y-axes chart with unified legend\n" ] } ], "source": [ "days_30 = np.arange(1, 31)\n", "cpu_load = 50 + 25 * np.sin(days_30 / 4.0) + rng.normal(0, 3, 30)\n", "connections = 2500 + 1500 * np.cos(days_30 / 5.0) + rng.normal(0, 100, 30)\n", "\n", "fig, ax1 = plt.subplots(figsize=(9, 4.5), dpi=100)\n", "l1 = ax1.plot(days_30, cpu_load, color='#1f77b4', lw=2, label='CPU Load (%)')\n", "ax1.set_xlabel('Day')\n", "ax1.set_ylabel('CPU Load (%)', color='#1f77b4', fontweight='bold')\n", "ax1.tick_params(axis='y', labelcolor='#1f77b4')\n", "ax1.grid(True, linestyle=':', alpha=0.5)\n", "\n", "ax2 = ax1.twinx()\n", "l2 = ax2.plot(days_30, connections, color='#ff7f0e', lw=2, linestyle='--', label='Active Connections')\n", "ax2.set_ylabel('Active Connections', color='#ff7f0e', fontweight='bold')\n", "ax2.tick_params(axis='y', labelcolor='#ff7f0e')\n", "\n", "lines = l1 + l2\n", "labels = [l.get_label() for l in lines]\n", "ax1.legend(lines, labels, loc='upper left')\n", "ax1.set_title('Server Telemetry: CPU Utilization vs User Connections', fontweight='bold')\n", "plt.show()\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": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Plot rendered: Log scale plot with minimalist Tufte-style outward spines\n" ] } ], "source": [ "x_log = np.linspace(1, 8, 50)\n", "y_log = 10**x_log\n", "\n", "fig, ax = plt.subplots(figsize=(7, 4.5), dpi=100)\n", "ax.plot(x_log, y_log, color='#2b5c8f', lw=2.2, marker='o', markersize=4)\n", "ax.set_yscale('log')\n", "ax.set_title('Exponential Growth on Clean Logarithmic Scale', fontweight='bold')\n", "ax.set_xlabel('Input Variable X')\n", "ax.set_ylabel('Metric Y (log10 scale)')\n", "ax.spines[['top', 'right']].set_visible(False)\n", "ax.spines['left'].set_position(('outward', 6))\n", "ax.spines['bottom'].set_position(('outward', 6))\n", "ax.grid(True, which='both', linestyle=':', alpha=0.4)\n", "plt.show()\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": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Export successful! File 'publication_plot.png' size: 38.42 KB\n" ] } ], "source": [ "import os\n", "x_pub = np.linspace(0, 15, 150)\n", "y_pub = np.cos(x_pub) * np.exp(-x_pub / 5.0)\n", "\n", "fig, ax = plt.subplots(figsize=(6, 3.5), dpi=100)\n", "ax.plot(x_pub, y_pub, color='#2b5c8f', lw=2)\n", "ax.set_title('Damped Cosine (300 DPI Export)', fontweight='bold')\n", "ax.set_xlabel('Time (s)')\n", "ax.set_ylabel('Amplitude')\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "ax.spines[['top', 'right']].set_visible(False)\n", "\n", "filename = 'publication_plot.png'\n", "fig.savefig(filename, dpi=300, bbox_inches='tight', facecolor='white')\n", "size_kb = os.path.getsize(filename) / 1024\n", "print(f\"Export successful! File '{filename}' size: {size_kb:.2f} KB\")\n", "os.remove(filename)\n", "plt.close(fig)\n" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.13.11" } }, "nbformat": 4, "nbformat_minor": 2 }