{"spec_id":"spectrogram-basic","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nspectrogram-basic: Spectrogram Time-Frequency Heatmap\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 84/100 | Updated: 2026-05-15\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import signal\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Generate a chirp signal (frequency increases over time)\nnp.random.seed(42)\nsample_rate = 4000  # Hz\nduration = 2.0  # seconds\nt = np.linspace(0, duration, int(sample_rate * duration))\n\n# Create chirp signal: frequency sweeps from 100 Hz to 1000 Hz\nf0 = 100  # Start frequency\nf1 = 1000  # End frequency\nsignal_data = np.sin(2 * np.pi * (f0 * t + (f1 - f0) * t**2 / (2 * duration)))\n\n# Add a second component: a tone burst in the middle\nburst_start = int(0.8 * sample_rate)\nburst_end = int(1.2 * sample_rate)\nburst_freq = 500  # Hz\nsignal_data[burst_start:burst_end] += 0.7 * np.sin(2 * np.pi * burst_freq * t[burst_start:burst_end])\n\n# Add some noise\nsignal_data += 0.1 * np.random.randn(len(signal_data))\n\n# Create figure\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Compute and plot spectrogram using scipy\nfreqs, times, Sxx = signal.spectrogram(signal_data, fs=sample_rate, nperseg=256, noverlap=200, scaling=\"density\")\n\n# Convert to dB scale\nSxx_db = 10 * np.log10(Sxx + 1e-10)\n\n# Plot spectrogram\nim = ax.pcolormesh(times, freqs, Sxx_db, shading=\"gouraud\", cmap=\"viridis\")\n\n# Add colorbar\ncbar = fig.colorbar(im, ax=ax, pad=0.02)\ncbar.set_label(\"Power/Frequency (dB/Hz)\", fontsize=20, color=INK)\ncbar.ax.tick_params(labelsize=16, colors=INK_SOFT)\nplt.setp(cbar.ax.get_yticklabels(), color=INK_SOFT)\n\n# Labels and styling\nax.set_xlabel(\"Time (s)\", fontsize=20, color=INK)\nax.set_ylabel(\"Frequency (Hz)\", fontsize=20, color=INK)\nax.set_title(\"spectrogram-basic · matplotlib · anyplot.ai\", fontsize=24, color=INK)\nax.tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT, labelcolor=INK_SOFT)\n\n# Style spines\nfor spine in (\"top\", \"right\"):\n    ax.spines[spine].set_visible(False)\nfor spine in (\"left\", \"bottom\"):\n    ax.spines[spine].set_color(INK_SOFT)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}