{"spec_id":"contour-density","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\ncontour-density: Density Contour Plot\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 79/100 | Updated: 2026-05-16\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\n\n\n# Data - bivariate distribution with two clusters\nnp.random.seed(42)\n\n# Cluster 1: Main cluster centered around (5, 5)\nn1 = 300\nx1 = np.random.normal(5, 1.5, n1)\ny1 = np.random.normal(5, 1.2, n1)\n\n# Cluster 2: Secondary cluster centered around (9, 8)\nn2 = 150\nx2 = np.random.normal(9, 0.8, n2)\ny2 = np.random.normal(8, 1.0, n2)\n\n# Combine clusters\nx = np.concatenate([x1, x2])\ny = np.concatenate([y1, y2])\n\n# Compute 2D kernel density estimation\nxmin, xmax = x.min() - 1, x.max() + 1\nymin, ymax = y.min() - 1, y.max() + 1\nxx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j]\npositions = np.vstack([xx.ravel(), yy.ravel()])\nvalues = np.vstack([x, y])\nkernel = stats.gaussian_kde(values)\ndensity = np.reshape(kernel(positions).T, xx.shape)\n\n# Plot\nfig, ax = plt.subplots(figsize=(16, 9))\n\n# Filled contours for visual impact\ncontourf = ax.contourf(xx, yy, density, levels=12, cmap=\"Blues\", alpha=0.8)\n\n# Contour lines for clarity\ncontour = ax.contour(xx, yy, density, levels=12, colors=\"#306998\", linewidths=1.5, alpha=0.9)\n\n# Scatter plot overlay for context (smaller, semi-transparent points)\nax.scatter(x, y, s=30, alpha=0.3, color=\"#FFD43B\", edgecolors=\"#306998\", linewidths=0.5, zorder=5)\n\n# Colorbar\ncbar = plt.colorbar(contourf, ax=ax, shrink=0.85, pad=0.02)\ncbar.set_label(\"Density\", fontsize=18)\ncbar.ax.tick_params(labelsize=14)\n\n# Labels and styling\nax.set_xlabel(\"X Variable\", fontsize=20)\nax.set_ylabel(\"Y Variable\", fontsize=20)\nax.set_title(\"contour-density · matplotlib · pyplots.ai\", fontsize=24)\nax.tick_params(axis=\"both\", labelsize=16)\nax.grid(True, alpha=0.3, linestyle=\"--\")\n\nplt.tight_layout()\nplt.savefig(\"plot.png\", dpi=300, bbox_inches=\"tight\")\n"}