Charts¶
Chart renders one or more marks against a shared dataset with Swift Charts. The marks are listed on Marks; axes and the legend are configured on the Chart.
Pages¶
| View | Description |
|---|---|
| Chart | The container: data, marks, axes, legend, backgrounds. |
| Marks | Every mark type, the parameters they share and the parameters of each. |
| ChartAxis & ChartLegend | Axis and legend configuration, PlottableField, PlottableValue and the chart enums. |
Quick example¶
import nib
def main(app: nib.App):
chart = nib.Chart(
data=[
{"month": "Jan", "sales": 100},
{"month": "Feb", "sales": 150},
{"month": "Mar", "sales": 200},
{"month": "Apr", "sales": 180},
],
marks=[nib.LineMark(x="month", y="sales", foreground_style="#3B82F6")],
x_axis=nib.ChartAxis(label="Month"),
y_axis=nib.ChartAxis(label="Sales", grid_lines=True),
width=350,
height=250,
padding=16,
)
app.build(chart)
nib.run(main)
Data model¶
data is a list of dicts, one dict per row. A mark names columns by key, and the runtime draws every mark once per row.
data = [
{"month": "Jan", "revenue": 4200, "expenses": 3100},
{"month": "Feb", "revenue": 5100, "expenses": 3400},
{"month": "Mar", "revenue": 4800, "expenses": 3200},
]
nib.Chart(data=data, marks=[nib.BarMark(x="month", y="revenue")])
- A row that lacks a key gets
Nonefor that column. A mark skips a row whose numeric column (y,angle, the RectMark bounds) isNone, NaN or infinite. - Values must be JSON-serializable: strings, numbers, booleans,
None. Adatetimeraises; pass a formatted string. - The SDK sends the data as columns encoded in one JSON string. You always work with rows.
Column types¶
| Position | Read as | Effect |
|---|---|---|
y (Line, Bar, Area, Point) |
number | Numeric strings such as "12" are parsed. Other strings skip the row. |
angle (SectorMark) |
number | Each sector is proportional to its value. |
x_start, x_end, y_start, y_end (RectMark) |
number |
PlottableField("col", type=...) states how a column is scaled: QUANTITATIVE on a numeric scale, NOMINAL as discrete categories, TEMPORAL on a time scale:
nib.LineMark(
x=nib.PlottableField("timestamp", type=nib.PlottableType.TEMPORAL),
y=nib.PlottableField("temperature", type=nib.PlottableType.QUANTITATIVE),
)
Column names and constants¶
Mark positions take a column name or a constant:
| Argument | Meaning |
|---|---|
"sales" |
The column sales. A string is always a column name in a position argument. |
nib.PlottableField("sales") |
The same column, written explicitly. |
150 (RuleMark only) |
The constant 150. |
nib.PlottableValue("Mar") (RuleMark only) |
A constant, here the x category "Mar". |
RuleMark(x="2024-06-15") therefore looks for a column named 2024-06-15. Use RuleMark(x=nib.PlottableValue("2024-06-15")) for a vertical rule at that category.
Choosing a mark¶
| Mark | Positions | Draws |
|---|---|---|
LineMark |
x, y |
A line through the rows. |
BarMark |
x, y |
One bar per row, vertical or horizontal. |
AreaMark |
x, y, optional y_start |
A filled area from zero, or from y_start, to the row's value. |
PointMark |
x, y |
One symbol per row: a scatter plot, or points over a line. |
RuleMark |
y or x, optional bounds |
A horizontal or vertical reference line. |
RectMark |
centres or bounds on each axis | Rectangles for heatmaps and range (Gantt) charts. |
SectorMark |
angle |
Pie and donut segments. |
Marks in one marks list share the data and the axes, so they layer:
data = [{"month": m, "sales": s} for m, s in zip(["Jan", "Feb", "Mar"], [120, 180, 150])]
chart = nib.Chart(
data=data,
marks=[
nib.AreaMark(x="month", y="sales", foreground_style="#3B82F6", opacity=0.2),
nib.LineMark(x="month", y="sales", foreground_style="#3B82F6"),
nib.PointMark(x="month", y="sales", foreground_style="#3B82F6"),
nib.RuleMark(y=150, line_width=1),
],
width=350,
height=220,
)
foreground_style¶
Every mark takes foreground_style. The SDK reads it as follows:
| Value | Result |
|---|---|
nib.PlottableField("series") |
Groups the rows by the series column. Swift Charts gives each distinct value its own colour and shows a legend. |
A string starting with # ("#3B82F6") or rgb ("rgb(59, 130, 246)") |
A fixed colour. |
One of white, black, red, green, blue, yellow, orange, purple, pink, cyan, magenta, gray, grey, brown, clear, transparent (any case) |
A fixed colour. |
| Any other string | A column name, the same as PlottableField. "teal" groups by a column named teal. |
nib.LinearGradient(...), nib.RadialGradient(...), nib.AngularGradient(...) |
A fixed gradient fill. |
A column whose name is in the colour list must be passed as PlottableField("red").
One line per series, coloured by the series column:
data = [
{"month": "Jan", "value": 100, "series": "Revenue"},
{"month": "Jan", "value": 80, "series": "Expenses"},
{"month": "Feb", "value": 150, "series": "Revenue"},
{"month": "Feb", "value": 90, "series": "Expenses"},
]
chart = nib.Chart(
data=data,
marks=[nib.LineMark(x="month", y="value", foreground_style=nib.PlottableField("series"))],
width=350,
height=220,
)
The same foreground_style on BarMark or AreaMark stacks the series; stacking picks the method.
Axes and legend¶
chart = nib.Chart(
data=data,
marks=[nib.LineMark(x="month", y="value", foreground_style=nib.PlottableField("series"))],
x_axis=nib.ChartAxis(label="Month"),
y_axis=nib.ChartAxis(label="Amount", grid_lines=True, format="currency"),
legend=nib.ChartLegend(position="bottom"),
)
- Without
x_axisory_axis, Swift Charts picks the axis marks. formatapplies to numeric tick values.legend=Falsehides the legend. The legend only has entries when a mark groups by a column throughforeground_styleorsymbol.
ChartAxis & ChartLegend lists every option.
Updating data¶
Assigning chart.data re-renders the chart. append_data, update_data and clear_data do the same for one change; see Chart.
Every update sends the whole dataset, not a delta. append_data also appends to the list you passed as data, since the chart keeps that list rather than a copy. For a live chart, keep a bounded window and assign a copy of it:
import collections, random, threading, time
import nib
def main(app: nib.App):
window = collections.deque(maxlen=30)
chart = nib.Chart(
data=[],
marks=[nib.LineMark(x="t", y="value")],
width=320,
height=180,
padding=16,
)
def sample():
while app.is_running:
window.append({"t": time.strftime("%H:%M:%S"), "value": random.randint(0, 100)})
chart.data = list(window)
time.sleep(1)
threading.Thread(target=sample, daemon=True).start()
app.build(chart)
nib.run(main)
Property writes are safe from any thread; see Reactivity.