Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                

Parliament Seat Chart in Bokeh (Python)

The same plot in 14 other libraries — Python: Altair, lets-plot, Matplotlib, Plotly, plotnine, Pygal, Seaborn; R: ggplot2; Julia: Makie.jl; JavaScript: Chart.js, D3.js, Apache ECharts, Highcharts, MUI X Charts. Compare all 15 side by side: Parliament Seat Chart in Python, R, Julia and JavaScript.

A semicircular parliament seat chart visualizes political party representation by arranging seats in concentric arcs. Each seat is displayed as an individual dot or segment, colored by party affiliation. This visualization is ideal for showing the composition of legislative bodies, election results, and voting bloc distributions at a glance.

Parliament Seat Chart rendered with Bokeh

Renders

Python source (Bokeh)

""" anyplot.ai
parliament-basic: Parliament Seat Chart
Library: bokeh 3.10.2 | Python 3.14.10
Quality: 84/100 | Updated: 2026-12-05
"""

import os
import time
from pathlib import Path

import numpy as np
import pandas as pd
from bokeh.io import output_file, save
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


# Theme tokens
THEME = os.getenv("ANYPLOT_THEME", "light")
PAGE_BG = "#FAF8F1" if THEME == "light" else "#1A1A17"
INK = "#1A1A17" if THEME == "light" else "#F0EFE8"
INK_SOFT = "#4A4A44" if THEME == "light" else "#B8B7B0"

# Imprint palette: all eight positions, one per party in data order
IMPRINT_PALETTE = ["#009E73", "#C475FD", "#4467A3", "#BD8233", "#AE3030", "#2ABCCD", "#954477", "#99B314"]

# Columns: set these to your table's column names
PARTY = "Party"  # role: party
SEATS = "Seats"  # role: seats
COLOR = "Color"  # role: color

# Data: replace this block with your own table, for example df = pd.read_csv("chamber.csv")
df = pd.DataFrame(
    {
        PARTY: ["Harbor Union", "Ember League", "Quarry Alliance", "Meadow Circle", "Cinder Forum", "Willow Bloc"],
        SEATS: [42, 52, 85, 58, 67, 96],
    }
)

# Plot: reads only df and the constants above
# Seat colors: the table's color column where it has one, else the Imprint positions in data order
in_order = [IMPRINT_PALETTE[i % len(IMPRINT_PALETTE)] for i in range(len(df))]
colors = df[COLOR].where(df[COLOR].notna(), in_order).tolist() if COLOR in df.columns else in_order
counts = df[SEATS].fillna(0).round().astype(int).to_numpy()
total = int(counts.sum())
majority = total // 2 + 1

# Concentric arcs: the seats per arc grow with its radius (largest-remainder rounding)
n_rows = 10
radii = 0.4 + 0.095 * np.arange(n_rows)
share = total * radii / radii.sum()
per_row = np.floor(share).astype(int)
order = np.argsort(share - per_row)[::-1]
per_row[order[: total - per_row.sum()]] += 1

# Every seat gets a position; sweeping the half circle from left to right makes each party one block
angle = np.concatenate([np.linspace(np.pi, 0, k) for k in per_row])
radius = np.repeat(radii, per_row)
sweep = np.lexsort((radius, -angle))
x = (radius * np.cos(angle))[sweep]
y = (radius * np.sin(angle))[sweep]
labels = [f"{party} · {count} seats" for party, count in zip(df[PARTY], counts, strict=True)]
seats = ColumnDataSource({"x": x, "y": y, "color": np.repeat(colors, counts), "label": np.repeat(labels, counts)})

# Square data units: pixels per unit follows from the plot area and the vertical range
W, H = 3200, 1800
border = 40
y_lo, y_hi = -0.9, radii.max() + 0.15
units_px = (H - 110 - border) / (y_hi - y_lo)
half_width = (W - 2 * border) / units_px / 2

p = figure(
    width=W,
    height=H,
    title="parliament-basic · python · bokeh · anyplot.ai",
    tools="",
    toolbar_location=None,
    x_range=(-half_width, half_width),
    y_range=(y_lo, y_hi),
    min_border_top=110,
    min_border_bottom=border,
    min_border_left=border,
    min_border_right=border,
)
# One glyph for all seats; legend_field groups it by party in sweep order (left to right)
p.scatter(x="x", y="y", source=seats, color="color", size=36, line_color=PAGE_BG, line_width=2, legend_field="label")

p.text(
    x=[0],
    y=[-0.12],
    text=[f"Majority threshold: {majority} of {total} seats"],
    text_align="center",
    text_font_size="26pt",
    text_font_style="bold",
    text_color=INK,
)

# Style
p.title.text_font_size = "50pt"
p.title.text_color = INK
p.title.align = "center"
p.xaxis.visible = False
p.yaxis.visible = False
p.xgrid.visible = False
p.ygrid.visible = False
p.outline_line_color = None
p.background_fill_color = PAGE_BG
p.border_fill_color = PAGE_BG

# Legend inside the empty band under the chamber, three parties per row
p.legend.location = "bottom_center"
p.legend.orientation = "horizontal"
p.legend.ncols = 3
p.legend.label_text_font_size = "34pt"
p.legend.label_text_color = INK_SOFT
# bokeh draws a scatter's legend key at a fraction of the glyph box: a larger box matches the seat size
p.legend.glyph_height = 90
p.legend.glyph_width = 90
p.legend.label_standoff = 4
p.legend.spacing = 48
p.legend.padding = 20
p.legend.margin = 30
p.legend.background_fill_alpha = 0
p.legend.border_line_color = None

# Save HTML
output_file(f"plot-{THEME}.html")
save(p)

# Screenshot with headless Chrome via Selenium
opts = Options()
for arg in (
    "--headless=new",
    "--no-sandbox",
    "--disable-dev-shm-usage",
    "--disable-gpu",
    f"--window-size={W},{H}",
    "--hide-scrollbars",
):
    opts.add_argument(arg)

driver = webdriver.Chrome(options=opts)
try:
    driver.set_window_size(W, H)
    driver.execute_cdp_cmd(
        "Emulation.setDeviceMetricsOverride", {"width": W, "height": H, "deviceScaleFactor": 1, "mobile": False}
    )
    driver.get(f"file://{Path(f'plot-{THEME}.html').resolve()}")
    driver.execute_script(
        "document.documentElement.style.background = arguments[0]; document.body.style.background = arguments[0];",
        PAGE_BG,
    )
    time.sleep(3)  # let bokeh's JS render the canvas
    driver.save_screenshot(f"plot-{THEME}.png")
finally:
    driver.quit()

Retrieve this implementation

Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/parliament-basic/bokeh/code. Any spec id and library id listed in llms-full.txt fit the same URL shape; every URL below is complete and callable.

{
  "spec_id": "parliament-basic",
  "language": "python",
  "library": "bokeh",
  "page": "https://anyplot.ai/parliament-basic/python/bokeh",
  "hub": "https://anyplot.ai/parliament-basic",
  "code_json": "https://api.anyplot.ai/specs/parliament-basic/bokeh/code",
  "spec_json": "https://api.anyplot.ai/specs/parliament-basic",
  "render_light_png": "https://storage.googleapis.com/anyplot-images/plots/parliament-basic/python/bokeh/plot-light.png",
  "render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/parliament-basic/python/bokeh/plot-dark.png",
  "interactive_light_html": "https://storage.googleapis.com/anyplot-images/plots/parliament-basic/python/bokeh/plot-light.html",
  "interactive_dark_html": "https://storage.googleapis.com/anyplot-images/plots/parliament-basic/python/bokeh/plot-dark.html",
  "quality_score": 84.0,
  "license": "MIT",
  "guide": "https://anyplot.ai/llms.txt"
}

Part of Parliament Seat Chart on anyplot.ai.

Other implementations