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

Bar Chart with Error Bars in Plotly (Python)

The same plot in 14 other libraries — Python: Altair, Bokeh, lets-plot, Matplotlib, 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: Bar Chart with Error Bars in Python, R, Julia and JavaScript.

A bar chart with error bars displays categorical data as rectangular bars with vertical (or horizontal) lines extending from each bar to indicate uncertainty or variability. Error bars typically represent standard deviation, standard error, confidence intervals, or min/max ranges. This visualization is essential for comparing group means while communicating the reliability and precision of each measurement.

Bar Chart with Error Bars rendered with Plotly

Renders

Python source (Plotly)

""" anyplot.ai
bar-error: Bar Chart with Error Bars
Library: plotly 7.1.0 | Python 3.14.10
Quality: 87/100 | Updated: 2026-12-03
"""

import os

import pandas as pd
import plotly.graph_objects as go


# Theme tokens (Imprint palette)
THEME = os.getenv("ANYPLOT_THEME", "light")
PAGE_BG = "#FAF8F1" if THEME == "light" else "#1A1A17"
ELEVATED_BG = "#FFFDF6" if THEME == "light" else "#242420"
INK = "#1A1A17" if THEME == "light" else "#F0EFE8"
INK_SOFT = "#4A4A44" if THEME == "light" else "#B8B7B0"
GRID = "rgba(26,26,23,0.15)" if THEME == "light" else "rgba(240,239,232,0.15)"
BRAND = "#009E73"  # Imprint palette position 1

# Columns: set these to your table's column names
GROUP = "Treatment"  # role: category
RESPONSE = "Cell viability (%)"  # role: value
ERR_LOW = "Lower error (SD, %)"  # role: error
ERR_HIGH = "Upper error (SD, %)"  # role: extra

# Data: replace this block with your own table, for example df = pd.read_csv("results.csv")
# Lab experiment comparing treatment effectiveness against a control; asymmetric errors (±1 SD)
df = pd.DataFrame(
    {
        GROUP: ["Control", "Metformin", "Rapamycin", "Resveratrol", "Quercetin"],
        RESPONSE: [45.2, 62.8, 58.3, 71.5, 55.9],
        ERR_LOW: [3.2, 7.8, 2.9, 8.1, 3.5],
        ERR_HIGH: [4.1, 9.2, 3.6, 11.3, 4.8],
    }
)

# Plot: reads only df and the constants above
# The first row is the control group, the reference for every treatment
control_name = df[GROUP].iloc[0]
control_value = df[RESPONSE].iloc[0]
axis_top = (df[RESPONSE] + df[ERR_HIGH]).max() * 1.087

fig = go.Figure()

fig.add_trace(
    go.Bar(
        x=df[GROUP],
        y=df[RESPONSE],
        marker=dict(color=BRAND, line=dict(color=INK_SOFT, width=1.5)),
        error_y=dict(
            type="data",
            symmetric=False,
            array=df[ERR_HIGH],
            arrayminus=df[ERR_LOW],
            color=INK_SOFT,
            thickness=2.5,
            width=8,
        ),
        name=RESPONSE,
        hovertemplate="<b>%{x}</b><br>Value: %{y:.1f}%<br>+%{error_y.array:.1f}% / -%{error_y.arrayminus:.1f}%<extra></extra>",
    )
)

# Dashed baseline at the control value so the reader sees which treatments beat the control
fig.add_hline(y=control_value, line=dict(color=INK_SOFT, width=1.5, dash="dash"))

fig.update_layout(
    autosize=False,
    title=dict(text="bar-error · python · plotly · anyplot.ai", font=dict(size=16, color=INK), x=0.5, xanchor="center"),
    xaxis=dict(
        title=dict(text=GROUP, font=dict(size=12, color=INK)),
        tickfont=dict(size=10, color=INK_SOFT),
        showgrid=False,
        showline=True,
        linecolor=INK_SOFT,
        linewidth=1,
        mirror=False,
        ticks="outside",
        tickcolor=INK_SOFT,
    ),
    yaxis=dict(
        title=dict(text=RESPONSE, font=dict(size=12, color=INK)),
        tickfont=dict(size=10, color=INK_SOFT),
        gridcolor=GRID,
        gridwidth=1,
        zeroline=False,
        showline=True,
        linecolor=INK_SOFT,
        linewidth=1,
        mirror=False,
        range=[0, axis_top],
    ),
    paper_bgcolor=PAGE_BG,
    plot_bgcolor=PAGE_BG,
    font=dict(color=INK),
    bargap=0.3,
    showlegend=False,
    margin=dict(l=80, r=40, t=80, b=60),
)

# Annotations in paper fractions, in the empty top corners above the bars
fig.add_annotation(
    text="Error bars: ±1 SD (asymmetric)",
    xref="paper",
    yref="paper",
    x=0.98,
    y=0.98,
    xanchor="right",
    yanchor="top",
    font=dict(size=10, color=INK_SOFT),
    showarrow=False,
)
fig.add_annotation(
    text=f"┄ {control_name} baseline ({control_value:.1f}%)",
    xref="paper",
    yref="paper",
    x=0.02,
    y=0.95,
    xanchor="left",
    yanchor="top",
    font=dict(size=10, color=INK_SOFT),
    showarrow=False,
)

# Theme-aware hover tooltip so the interactive HTML stays legible in dark mode too.
fig.update_traces(hoverlabel=dict(bgcolor=ELEVATED_BG, bordercolor=INK_SOFT, font=dict(color=INK, size=10)))

# Hard target: 3200 x 1800 (landscape). See prompts/library/plotly.md "Canvas".
fig.write_image(f"plot-{THEME}.png", width=800, height=450, scale=4)
fig.write_html(f"plot-{THEME}.html", include_plotlyjs="cdn")

Retrieve this implementation

Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/bar-error/plotly/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": "bar-error",
  "language": "python",
  "library": "plotly",
  "page": "https://anyplot.ai/bar-error/python/plotly",
  "hub": "https://anyplot.ai/bar-error",
  "code_json": "https://api.anyplot.ai/specs/bar-error/plotly/code",
  "spec_json": "https://api.anyplot.ai/specs/bar-error",
  "render_light_png": "https://storage.googleapis.com/anyplot-images/plots/bar-error/python/plotly/plot-light.png",
  "render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/bar-error/python/plotly/plot-dark.png",
  "interactive_light_html": "https://storage.googleapis.com/anyplot-images/plots/bar-error/python/plotly/plot-light.html",
  "interactive_dark_html": "https://storage.googleapis.com/anyplot-images/plots/bar-error/python/plotly/plot-dark.html",
  "quality_score": 87.0,
  "license": "MIT",
  "guide": "https://anyplot.ai/llms.txt"
}

Part of Bar Chart with Error Bars on anyplot.ai.

Other implementations