{"spec_id":"pie-basic","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\npie-basic: Basic Pie Chart\nLibrary: plotnine 0.15.9 | Python 3.14.10\nQuality: 85/100 | Updated: 2026-11-28\n\"\"\"\n\nimport os\nimport sys\n\n\n# Remove this file's directory from sys.path to prevent self-import\n# (this file is named plotnine.py, same as the library being imported)\n_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p) != _dir]\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    coord_equal,\n    element_rect,\n    element_text,\n    geom_polygon,\n    geom_segment,\n    geom_text,\n    ggplot,\n    labs,\n    scale_color_identity,\n    scale_fill_manual,\n    theme,\n    theme_void,\n)\n\n\n# Theme tokens\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\"\n\n# Imprint palette: all eight positions, one per slice in order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Constants\nEXPLODE_OFFSET = 0.07  # how far the largest slice is pulled out, in radii\nSMALL_SHARE = 0.06  # slices narrower than this get their label outside with a leader line\nDARK_TEXT = \"#1A1A17\"  # text on light slices, in both themes (slice colors do not change)\n\n# Columns: set these to your table's column names\nCATEGORY = \"Commute mode\"  # role: category\nVALUE = \"Share of commuters (%)\"  # role: value\n\n# Data: replace this block with your own table, for example df = pd.read_csv(\"shares.csv\")\ndf = pd.DataFrame(\n    {CATEGORY: [\"Car\", \"Public transit\", \"Walking\", \"Cycling\", \"Remote work\", \"Other\"], VALUE: [41, 23, 12, 10, 10, 4]}\n)\n\n# Plot: reads only df and the constants above\ncategories = df[CATEGORY].tolist()\nshares = df[VALUE] / df[VALUE].sum()\nlargest = int(df[VALUE].to_numpy().argmax())\n\n# Wedge polygons start at 12 o'clock and run clockwise\nends = shares.cumsum().to_numpy()\nstarts = ends - shares.to_numpy()\nwedge_rows = []\nlabel_rows = []\nsegment_rows = []\nfor i, cat in enumerate(categories):\n    start_angle = np.pi / 2 - 2 * np.pi * starts[i]\n    end_angle = np.pi / 2 - 2 * np.pi * ends[i]\n    mid_angle = (start_angle + end_angle) / 2\n    offset = EXPLODE_OFFSET if i == largest else 0.0\n    dx, dy = offset * np.cos(mid_angle), offset * np.sin(mid_angle)\n\n    arc = np.linspace(start_angle, end_angle, 80)\n    xs = np.concatenate([[0.0], np.cos(arc)]) + dx\n    ys = np.concatenate([[0.0], np.sin(arc)]) + dy\n    wedge_rows.append(pd.DataFrame({\"x\": xs, \"y\": ys, \"category\": cat}))\n\n    label = f\"{shares.iloc[i] * 100:.0f}%\"\n    if not shares.iloc[i] < SMALL_SHARE:\n        # Inside the slice; dark or white text, whichever contrasts with the slice color\n        r, g, b = (int(IMPRINT_PALETTE[i][k : k + 2], 16) / 255 for k in (1, 3, 5))\n        luminance = 0.2126 * r**3 + 0.7152 * g**3 + 0.0722 * b**3  # cheap gamma-ish approximation\n        text_color = DARK_TEXT if luminance > 0.12 else \"#FFFFFF\"\n        label_r = 0.62 + offset\n        label_rows.append(\n            {\n                \"x\": label_r * np.cos(mid_angle) + dx,\n                \"y\": label_r * np.sin(mid_angle) + dy,\n                \"label\": label,\n                \"ink\": text_color,\n            }\n        )\n    else:\n        # Narrow slice: label beside it, tied to the slice edge by a short leader line\n        segment_rows.append(\n            {\n                \"x\": 1.0 * np.cos(mid_angle),\n                \"y\": 1.0 * np.sin(mid_angle),\n                \"xend\": 1.12 * np.cos(mid_angle),\n                \"yend\": 1.12 * np.sin(mid_angle),\n            }\n        )\n        label_rows.append({\"x\": 1.22 * np.cos(mid_angle), \"y\": 1.22 * np.sin(mid_angle), \"label\": label, \"ink\": INK})\n\ndf_wedges = pd.concat(wedge_rows, ignore_index=True)\ndf_wedges[\"category\"] = pd.Categorical(df_wedges[\"category\"], categories=categories, ordered=True)\ndf_labels = pd.DataFrame(label_rows)\ndf_segments = pd.DataFrame(segment_rows)\n\nleader_lines = (\n    geom_segment(data=df_segments, mapping=aes(x=\"x\", y=\"y\", xend=\"xend\", yend=\"yend\"), color=INK_SOFT, size=0.5)\n    if len(df_segments)\n    else []\n)\n\nplot = (\n    ggplot()\n    + geom_polygon(data=df_wedges, mapping=aes(x=\"x\", y=\"y\", fill=\"category\", group=\"category\"))\n    + leader_lines\n    + geom_text(data=df_labels, mapping=aes(x=\"x\", y=\"y\", label=\"label\", color=\"ink\"), size=8.0)\n    + scale_fill_manual(values=IMPRINT_PALETTE, limits=categories)\n    + scale_color_identity()\n    + coord_equal()\n    + labs(title=\"pie-basic · python · plotnine · anyplot.ai\", fill=CATEGORY)\n    + theme_void()\n    + theme(\n        figure_size=(6, 6),\n        plot_margin_right=0.04,\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG),\n        plot_title=element_text(size=12, color=INK, ha=\"center\"),\n        legend_text=element_text(size=9, color=INK_SOFT),\n        legend_title=element_text(size=10, color=INK),\n        legend_background=element_rect(fill=ELEVATED_BG, color=INK_SOFT),\n        legend_key=element_rect(fill=ELEVATED_BG, color=ELEVATED_BG),\n    )\n)\n\n# Draw and save; subplots_adjust gives the right-side legend room\nfig = plot.draw()\nfig.subplots_adjust(left=0.02, right=0.76)\nfig.savefig(f\"plot-{THEME}.png\", dpi=400)\nplt.close(fig)\n"}