---
name: data-visualization
description: Visualize data as a chart, plot, diagram or graph - line, bar, scatter, histogram, box plot, pie, heatmap, area. Default output is a PNG made with Python/matplotlib; an interactive HTML page (Plotly) when the task asks for HTML, a web page or interactivity.
---
# Data visualization
Two output paths. Pick ONE:
| Task says | Output | How |
|---|---|---|
| nothing special, "plot", "chart", "diagram", PNG, report | `chart.png` | Python + matplotlib (section A) - the default |
| "HTML", "web page", "interactive", "browser", "dashboard" | `chart.html` | Plotly page from `template.html` (section B) |
## 1. Choose the chart type
| The data shows | Chart |
|---|---|
| change over time / ordered x | line (area if the filled quantity matters) |
| values per category | bar (horizontal if labels are long or there are > 8 categories) |
| categories split into sub-groups | grouped bar (compare groups) or stacked bar (show totals) |
| relation between two numeric variables | scatter |
| distribution of one variable | histogram |
| distributions of several groups side by side | box plot |
| parts of one whole, at most 5 parts | pie / donut (otherwise use a bar chart) |
| value for every cell of a grid / matrix / correlation | heatmap |
## 2. Rules for every chart
- Plot the real data of the task. Read files (CSV, JSON) with code; never retype or invent values.
- Title that states what is shown; axis labels WITH units; legend only if there are 2+ series.
- Labels in the language of the task.
- Bar charts start at zero. Sort bars by value unless the categories have a natural order.
- No 3D, no decoration. At most ~6 series per chart; more -> several panels.
- Dates on the x-axis must be real dates (`pd.to_datetime` / ISO strings), not arbitrary text.
## A. Python / matplotlib (default)
Write a script `plot.py`, run it, then look at the result.
```python
import matplotlib
matplotlib.use("Agg") # headless - NEVER call plt.show(), it blocks until the timeout
import matplotlib.pyplot as plt
x = [2019, 2020, 2021, 2022, 2023]
y = [12.1, 9.8, 13.4, 15.0, 16.2]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(x, y, marker="o") # <- the drawing call, see the table below
ax.set_title("Revenue per year")
ax.set_xlabel("Year")
ax.set_ylabel("Revenue (million EUR)")
ax.grid(alpha=0.3)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("chart.png", dpi=150)
print("saved chart.png")
```
Drawing calls (replace the `ax.plot` line):
| Chart | Call |
|---|---|
| line | `ax.plot(x, y, marker="o", label="A")` - once per series, then `ax.legend()` |
| area | `ax.fill_between(x, y, alpha=0.4)`; stacked: `ax.stackplot(x, y1, y2, labels=["A", "B"])` |
| bar | `ax.bar(cats, vals)`; horizontal: `ax.barh(cats, vals)` |
| grouped bar | `import numpy as np; i = np.arange(len(cats)); w = 0.4`
`ax.bar(i - w/2, a, w, label="A"); ax.bar(i + w/2, b, w, label="B"); ax.set_xticks(i, cats)` |
| stacked bar | `ax.bar(cats, a, label="A"); ax.bar(cats, b, bottom=a, label="B")` |
| scatter | `ax.scatter(x, y, alpha=0.7)`; 3rd variable: `s=sizes` or `c=values, cmap="viridis"` |
| histogram | `ax.hist(values, bins=20, edgecolor="white")` |
| box plot | `ax.boxplot([a, b, c]); ax.set_xticks([1, 2, 3], ["A", "B", "C"])` |
| pie | `ax.pie(vals, labels=cats, autopct="%1.0f%%", startangle=90)`; donut: add `wedgeprops={"width": 0.4}`; no grid/axis labels |
| heatmap | `im = ax.imshow(matrix, cmap="viridis", aspect="auto"); fig.colorbar(im, label="unit")`
`ax.set_xticks(range(len(cols)), cols); ax.set_yticks(range(len(rows)), rows)`; no grid |
More:
- Several panels: `fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))`, then draw on `axes[0]`, `axes[1]`.
- Data from a file: `import pandas as pd; df = pd.read_csv("data.csv")`, then `df["column"]`. Print `df.head()` and `df.dtypes` once before plotting, so you use the real column names.
- Long category labels: `ax.barh` or `ax.tick_params(axis="x", rotation=45)`.
- Value labels on bars: `ax.bar_label(ax.bar(cats, vals), fmt="%.1f")`.
- Missing library: `pip install matplotlib pandas`.
Check (mandatory):
1. `run_command`: `python plot.py` must exit with 0 and print `saved chart.png`.
2. `view_image("chart.png")` and check what you SEE: all series/categories present, labels readable and not overlapping, nothing cut off, values plausible compared with the data. Fix and re-run if not.
## B. HTML / Plotly (only when asked for)
One self-contained page; the data sits in a JSON block, Plotly (loaded from a CDN, so the page needs internet) draws it.
1. Copy the template: `cp /template.html chart.html`
2. Replace the JSON block `{"traces": [], "layout": {}}` in `chart.html` and the ``:
- few values: with `edit_file`, write the JSON by hand;
- data from a file or more than ~30 values: with a Python script:
```python
import json, pandas as pd
df = pd.read_csv("data.csv")
spec = {"traces": [{"type": "bar", "x": df["city"].tolist(), "y": df["population"].tolist()}],
"layout": {"title": {"text": "Population per city"},
"xaxis": {"title": {"text": "City"}}, "yaxis": {"title": {"text": "Inhabitants"}}}}
html = open("chart.html", encoding="utf-8").read()
html = html.replace('{"traces": [], "layout": {}}', json.dumps(spec, ensure_ascii=False))
html = html.replace("Chart", "Population per city")
open("chart.html", "w", encoding="utf-8").write(html)
```
3. Check: `python /check_html.py chart.html` must print `OK`.
Traces (each trace is one series; put several in the `traces` list):
| Chart | Trace | Layout extras |
|---|---|---|
| line | `{"type": "scatter", "mode": "lines+markers", "x": [...], "y": [...], "name": "A"}` | |
| area | line trace + `"fill": "tozeroy"`; stacked: `"stackgroup": "one"` instead | |
| bar | `{"type": "bar", "x": cats, "y": vals, "name": "A"}`; horizontal: swap x/y and add `"orientation": "h"` | |
| grouped / stacked bar | one bar trace per group | `"barmode": "group"` or `"stack"` |
| scatter | `{"type": "scatter", "mode": "markers", "x": [...], "y": [...]}` | |
| histogram | `{"type": "histogram", "x": values, "nbinsx": 20}` | |
| box plot | one `{"type": "box", "y": values, "name": "A"}` per group | |
| pie | `{"type": "pie", "labels": cats, "values": vals}`; donut: add `"hole": 0.5` | |
| heatmap | `{"type": "heatmap", "z": matrix, "x": cols, "y": rows, "colorscale": "Viridis"}` | |
Layout: `{"title": {"text": "..."}, "xaxis": {"title": {"text": "... (unit)"}}, "yaxis": {"title": {"text": "... (unit)"}}}`.
JSON only: double quotes, no trailing commas, no comments, no `NaN` (use `null`).