{"spec_id":"pp-basic","library":"letsplot","language":"python","code":"\"\"\" anyplot.ai\npp-basic: Probability-Probability (P-P) Plot\nLibrary: letsplot 4.10.1 | Python 3.13.13\nQuality: 93/100 | Updated: 2026-06-16\n\"\"\"\n\nimport os\nfrom math import erf, sqrt\n\nimport numpy as np\nimport pandas as pd\nfrom lets_plot import *\n\n\nLetsPlot.setup_html()\n\n# Theme tokens (see prompts/default-style-guide.md \"Theme-adaptive Chrome\")\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n# Subtle gridline (~15% INK over PAGE_BG, per style guide rgba(...,0.15))\nGRID = \"#D8D7D0\" if THEME == \"light\" else \"#3A3A36\"\n\n# Imprint diverging cmap: matte-red <-> near-neutral (page bg) <-> blue\nIMPRINT_DIV_LOW = \"#AE3030\"\nIMPRINT_DIV_MID = PAGE_BG\nIMPRINT_DIV_HIGH = \"#4467A3\"\n\n# Data: pharmaceutical tablet weight measurements (mg) from a filling machine\n# Real-world QC scenario - checking if weights follow a normal distribution\nnp.random.seed(42)\nn_samples = 200\n\n# Tablet weights: target 500mg, slight right skew from occasional overfills\nnormal_fill = np.random.normal(500, 8, 160)\noverfill_events = np.random.exponential(5, 40) + 498\nobserved = np.concatenate([normal_fill, overfill_events])\nobserved = observed[:n_samples]\n\n# Sort observed data\nobserved_sorted = np.sort(observed)\n\n# Compute empirical CDF using plotting position formula i/(n+1)\nempirical_cdf = np.arange(1, n_samples + 1) / (n_samples + 1)\n\n# Fit normal distribution (MLE: mean and std of data)\nmu = np.mean(observed_sorted)\nsigma = np.std(observed_sorted, ddof=0)\n\n# Compute theoretical CDF values (normal CDF inline)\nz_scores = (observed_sorted - mu) / (sigma * sqrt(2))\ntheoretical_cdf = 0.5 * (1 + np.vectorize(erf)(z_scores))\n\n# Signed deviation from perfect fit drives the diverging color mapping\ndeviation = empirical_cdf - theoretical_cdf\n\n# Classify deviation region for tooltips\nregion = np.where(np.abs(deviation) < 0.02, \"Near fit\", np.where(deviation > 0, \"Above diagonal\", \"Below diagonal\"))\n\n# Create dataframe for P-P plot points\ndf_pp = pd.DataFrame(\n    {\n        \"theoretical\": theoretical_cdf,\n        \"empirical\": empirical_cdf,\n        \"deviation\": deviation,\n        \"abs_deviation\": np.abs(deviation),\n        \"weight\": observed_sorted,\n        \"region\": region,\n    }\n)\n\n# Confidence envelope around diagonal (approximate 95% Kolmogorov band)\nks_band = 1.36 / sqrt(n_samples)\nenvelope_x = np.linspace(0, 1, 100)\ndf_envelope = pd.DataFrame(\n    {\n        \"x\": envelope_x,\n        \"y_upper\": np.minimum(envelope_x + ks_band, 1.0),\n        \"y_lower\": np.maximum(envelope_x - ks_band, 0.0),\n    }\n)\n\n# Reference line (perfect fit diagonal)\ndf_ref = pd.DataFrame({\"x\": [0, 1], \"y\": [0, 1]})\n\n# Annotation for max deviation - placed in the empty lower-right triangle to avoid overlap\nmax_dev_idx = np.argmax(np.abs(deviation))\ndf_annotation = pd.DataFrame({\"x\": [0.58], \"y\": [0.12], \"label\": [f\"Max deviation: {deviation[max_dev_idx]:+.3f}\"]})\n\n# Plot with lets-plot distinctive features: tooltips, theme-adaptive chrome, text annotation\nplot = (\n    ggplot()\n    + geom_ribbon(\n        aes(x=\"x\", ymin=\"y_lower\", ymax=\"y_upper\"),\n        data=df_envelope,\n        fill=INK_MUTED,\n        alpha=0.18,\n        size=0,\n        tooltips=layer_tooltips().line(\"95% Kolmogorov band\"),\n    )\n    + geom_line(aes(x=\"x\", y=\"y\"), data=df_ref, color=INK, size=1.0, linetype=\"dashed\", tooltips=\"none\")\n    + geom_point(\n        aes(x=\"theoretical\", y=\"empirical\", fill=\"deviation\", size=\"abs_deviation\"),\n        data=df_pp,\n        shape=21,\n        color=INK_SOFT,\n        stroke=0.7,\n        alpha=0.65,\n        tooltips=layer_tooltips()\n        .format(\"weight\", \".1f\")\n        .format(\"deviation\", \"+.4f\")\n        .line(\"@|@weight mg\")\n        .line(\"Deviation|@deviation\")\n        .line(\"@region\"),\n    )\n    + geom_text(\n        aes(x=\"x\", y=\"y\", label=\"label\"), data=df_annotation, size=6, color=INK_SOFT, hjust=0, fontface=\"italic\"\n    )\n    + scale_fill_gradient2(\n        low=IMPRINT_DIV_LOW,\n        mid=IMPRINT_DIV_MID,\n        high=IMPRINT_DIV_HIGH,\n        midpoint=0,\n        name=\"Deviation\\n(Empirical − Theoretical)\",\n    )\n    + scale_size(range=[2, 5], guide=\"none\")\n    + labs(\n        x=\"Theoretical CDF (Normal)\",\n        y=\"Empirical CDF\",\n        title=\"pp-basic · python · letsplot · anyplot.ai\",\n        subtitle=\"QC Check: Tablet Weight Distribution vs. Normal Reference (n=200)\",\n    )\n    + scale_x_continuous(limits=[0, 1], breaks=[0, 0.2, 0.4, 0.6, 0.8, 1.0])\n    + scale_y_continuous(limits=[0, 1], breaks=[0, 0.2, 0.4, 0.6, 0.8, 1.0])\n    + coord_fixed(ratio=1)\n    + theme_minimal()\n    + theme(\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_grid_major=element_line(color=GRID, size=0.3),\n        panel_grid_minor=element_blank(),\n        plot_title=element_text(size=16, face=\"bold\", color=INK),\n        plot_subtitle=element_text(size=11, color=INK_SOFT),\n        axis_title=element_text(size=12, color=INK),\n        axis_text=element_text(size=10, color=INK_SOFT),\n        axis_line=element_line(color=INK_SOFT, size=0.4),\n        legend_background=element_rect(fill=ELEVATED_BG, color=INK_SOFT),\n        legend_title=element_text(size=11, color=INK),\n        legend_text=element_text(size=10, color=INK_SOFT),\n        legend_position=\"right\",\n    )\n    + ggsize(600, 600)\n)\n\n# Save (square 2400 x 2400: ggsize 600 x scale 4)\nggsave(plot, f\"plot-{THEME}.png\", path=\".\", scale=4)\nggsave(plot, f\"plot-{THEME}.html\", path=\".\")\n"}