Create custom charts and visualizations.
This is the multi-page printable view of this section. Click here to print.
Custom Charts
- 1: bar()
- 2: confusion_matrix()
- 3: histogram()
- 4: line_series()
- 5: line()
- 6: plot
- 7: plot_table()
- 8: pr_curve()
- 9: roc_curve()
- 10: scatter()
- 11: visualize()
1 - bar()
function bar
bar(
table: 'wandb.Table',
label: 'str',
value: 'str',
title: 'str' = '',
split_table: 'bool' = False
) → CustomChart
Constructs a bar chart from a wandb.Table of data.
Args:
table
: A table containing the data for the bar chart.label
: The name of the column to use for the labels of each bar.value
: The name of the column to use for the values of each bar.title
: The title of the bar chart.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Example:
import random
import wandb
# Generate random data for the table
data = [
["car", random.uniform(0, 1)],
["bus", random.uniform(0, 1)],
["road", random.uniform(0, 1)],
["person", random.uniform(0, 1)],
]
# Create a table with the data
table = wandb.Table(data=data, columns=["class", "accuracy"])
# Initialize a W&B run and log the bar plot
with wandb.init(project="bar_chart") as run:
# Create a bar plot from the table
bar_plot = wandb.plot.bar(
table=table,
label="class",
value="accuracy",
title="Object Classification Accuracy",
)
# Log the bar chart to W&B
run.log({"bar_plot": bar_plot})
2 - confusion_matrix()
function confusion_matrix
confusion_matrix(
probs: 'Sequence[Sequence[float]] | None' = None,
y_true: 'Sequence[T] | None' = None,
preds: 'Sequence[T] | None' = None,
class_names: 'Sequence[str] | None' = None,
title: 'str' = 'Confusion Matrix Curve',
split_table: 'bool' = False
) → CustomChart
Constructs a confusion matrix from a sequence of probabilities or predictions.
Args:
probs
: A sequence of predicted probabilities for each class. The sequence shape should be (N, K) where N is the number of samples and K is the number of classes. If provided,preds
should not be provided.y_true
: A sequence of true labels.preds
: A sequence of predicted class labels. If provided,probs
should not be provided.class_names
: Sequence of class names. If not provided, class names will be defined as “Class_1”, “Class_2”, etc.title
: Title of the confusion matrix chart.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Raises:
ValueError
: If bothprobs
andpreds
are provided or if the number of predictions and true labels are not equal. If the number of unique predicted classes exceeds the number of class names or if the number of unique true labels exceeds the number of class names.wandb.Error
: If numpy is not installed.
Examples: Logging a confusion matrix with random probabilities for wildlife classification:
import numpy as np
import wandb
# Define class names for wildlife
wildlife_class_names = ["Lion", "Tiger", "Elephant", "Zebra"]
# Generate random true labels (0 to 3 for 10 samples)
wildlife_y_true = np.random.randint(0, 4, size=10)
# Generate random probabilities for each class (10 samples x 4 classes)
wildlife_probs = np.random.rand(10, 4)
wildlife_probs = np.exp(wildlife_probs) / np.sum(
np.exp(wildlife_probs),
axis=1,
keepdims=True,
)
# Initialize W&B run and log confusion matrix
with wandb.init(project="wildlife_classification") as run:
confusion_matrix = wandb.plot.confusion_matrix(
probs=wildlife_probs,
y_true=wildlife_y_true,
class_names=wildlife_class_names,
title="Wildlife Classification Confusion Matrix",
)
run.log({"wildlife_confusion_matrix": confusion_matrix})
In this example, random probabilities are used to generate a confusion matrix.
Logging a confusion matrix with simulated model predictions and 85% accuracy:
import numpy as np
import wandb
# Define class names for wildlife
wildlife_class_names = ["Lion", "Tiger", "Elephant", "Zebra"]
# Simulate true labels for 200 animal images (imbalanced distribution)
wildlife_y_true = np.random.choice(
[0, 1, 2, 3],
size=200,
p=[0.2, 0.3, 0.25, 0.25],
)
# Simulate model predictions with 85% accuracy
wildlife_preds = [
y_t
if np.random.rand() < 0.85
else np.random.choice([x for x in range(4) if x != y_t])
for y_t in wildlife_y_true
]
# Initialize W&B run and log confusion matrix
with wandb.init(project="wildlife_classification") as run:
confusion_matrix = wandb.plot.confusion_matrix(
preds=wildlife_preds,
y_true=wildlife_y_true,
class_names=wildlife_class_names,
title="Simulated Wildlife Classification Confusion Matrix",
)
run.log({"wildlife_confusion_matrix": confusion_matrix})
In this example, predictions are simulated with 85% accuracy to generate a confusion matrix.
3 - histogram()
function histogram
histogram(
table: 'wandb.Table',
value: 'str',
title: 'str' = '',
split_table: 'bool' = False
) → CustomChart
Constructs a histogram chart from a W&B Table.
Args:
table
: The W&B Table containing the data for the histogram.value
: The label for the bin axis (x-axis).title
: The title of the histogram plot.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Example:
import math
import random
import wandb
# Generate random data
data = [[i, random.random() + math.sin(i / 10)] for i in range(100)]
# Create a W&B Table
table = wandb.Table(
data=data,
columns=["step", "height"],
)
# Create a histogram plot
histogram = wandb.plot.histogram(
table,
value="height",
title="My Histogram",
)
# Log the histogram plot to W&B
with wandb.init(...) as run:
run.log({"histogram-plot1": histogram})
4 - line_series()
function line_series
line_series(
xs: 'Iterable[Iterable[Any]] | Iterable[Any]',
ys: 'Iterable[Iterable[Any]]',
keys: 'Iterable[str] | None' = None,
title: 'str' = '',
xname: 'str' = 'x',
split_table: 'bool' = False
) → CustomChart
Constructs a line series chart.
Args:
xs
: Sequence of x values. If a singular array is provided, all y values are plotted against that x array. If an array of arrays is provided, each y value is plotted against the corresponding x array.ys
: Sequence of y values, where each iterable represents a separate line series.keys
: Sequence of keys for labeling each line series. If not provided, keys will be automatically generated as “line_1”, “line_2”, etc.title
: Title of the chart.xname
: Label for the x-axis.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Examples: Logging a single x array where all y series are plotted against the same x values:
import wandb
# Initialize W&B run
with wandb.init(project="line_series_example") as run:
# x values shared across all y series
xs = list(range(10))
# Multiple y series to plot
ys = [
[i for i in range(10)], # y = x
[i**2 for i in range(10)], # y = x^2
[i**3 for i in range(10)], # y = x^3
]
# Generate and log the line series chart
line_series_chart = wandb.plot.line_series(
xs,
ys,
title="title",
xname="step",
)
run.log({"line-series-single-x": line_series_chart})
In this example, a single xs
series (shared x-values) is used for all ys
series. This results in each y-series being plotted against the same x-values (0-9).
Logging multiple x arrays where each y series is plotted against its corresponding x array:
import wandb
# Initialize W&B run
with wandb.init(project="line_series_example") as run:
# Separate x values for each y series
xs = [
[i for i in range(10)], # x for first series
[2 * i for i in range(10)], # x for second series (stretched)
[3 * i for i in range(10)], # x for third series (stretched more)
]
# Corresponding y series
ys = [
[i for i in range(10)], # y = x
[i**2 for i in range(10)], # y = x^2
[i**3 for i in range(10)], # y = x^3
]
# Generate and log the line series chart
line_series_chart = wandb.plot.line_series(
xs, ys, title="Multiple X Arrays Example", xname="Step"
)
run.log({"line-series-multiple-x": line_series_chart})
In this example, each y series is plotted against its own unique x series. This allows for more flexibility when the x values are not uniform across the data series.
Customizing line labels using keys
:
import wandb
# Initialize W&B run
with wandb.init(project="line_series_example") as run:
xs = list(range(10)) # Single x array
ys = [
[i for i in range(10)], # y = x
[i**2 for i in range(10)], # y = x^2
[i**3 for i in range(10)], # y = x^3
]
# Custom labels for each line
keys = ["Linear", "Quadratic", "Cubic"]
# Generate and log the line series chart
line_series_chart = wandb.plot.line_series(
xs,
ys,
keys=keys, # Custom keys (line labels)
title="Custom Line Labels Example",
xname="Step",
)
run.log({"line-series-custom-keys": line_series_chart})
This example shows how to provide custom labels for the lines using the keys
argument. The keys will appear in the legend as “Linear”, “Quadratic”, and “Cubic”.
5 - line()
function line
line(
table: 'wandb.Table',
x: 'str',
y: 'str',
stroke: 'str | None' = None,
title: 'str' = '',
split_table: 'bool' = False
) → CustomChart
Constructs a customizable line chart.
Args:
table
: The table containing data for the chart.x
: Column name for the x-axis values.y
: Column name for the y-axis values.stroke
: Column name to differentiate line strokes (e.g., for grouping lines).title
: Title of the chart.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Example:
import math
import random
import wandb
# Create multiple series of data with different patterns
data = []
for i in range(100):
# Series 1: Sinusoidal pattern with random noise
data.append([i, math.sin(i / 10) + random.uniform(-0.1, 0.1), "series_1"])
# Series 2: Cosine pattern with random noise
data.append([i, math.cos(i / 10) + random.uniform(-0.1, 0.1), "series_2"])
# Series 3: Linear increase with random noise
data.append([i, i / 10 + random.uniform(-0.5, 0.5), "series_3"])
# Define the columns for the table
table = wandb.Table(data=data, columns=["step", "value", "series"])
# Initialize wandb run and log the line chart
with wandb.init(project="line_chart_example") as run:
line_chart = wandb.plot.line(
table=table,
x="step",
y="value",
stroke="series", # Group by the "series" column
title="Multi-Series Line Plot",
)
run.log({"line-chart": line_chart})
6 - plot
module wandb
Chart Visualization Utilities
This module offers a collection of predefined chart types, along with functionality for creating custom charts, enabling flexible visualization of your data beyond the built-in options.
7 - plot_table()
function plot_table
plot_table(
vega_spec_name: 'str',
data_table: 'wandb.Table',
fields: 'dict[str, Any]',
string_fields: 'dict[str, Any] | None' = None,
split_table: 'bool' = False
) → CustomChart
Creates a custom charts using a Vega-Lite specification and a wandb.Table
.
This function creates a custom chart based on a Vega-Lite specification and a data table represented by a wandb.Table
object. The specification needs to be predefined and stored in the W&B backend. The function returns a custom chart object that can be logged to W&B using wandb.log()
.
Args:
vega_spec_name
: The name or identifier of the Vega-Lite spec that defines the visualization structure.data_table
: Awandb.Table
object containing the data to be visualized.fields
: A mapping between the fields in the Vega-Lite spec and the corresponding columns in the data table to be visualized.string_fields
: A dictionary for providing values for any string constants required by the custom visualization.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Raises:
wandb.Error
: Ifdata_table
is not awandb.Table
object.
Example:
# Create a custom chart using a Vega-Lite spec and the data table.
import wandb
wandb.init()
data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
table = wandb.Table(data=data, columns=["x", "y"])
fields = {"x": "x", "y": "y", "title": "MY TITLE"}
# Create a custom title with `string_fields`.
my_custom_chart = wandb.plot_table(
vega_spec_name="wandb/line/v0",
data_table=table,
fields=fields,
string_fields={"title": "Title"},
)
wandb.log({"custom_chart": my_custom_chart})
8 - pr_curve()
function pr_curve
pr_curve(
y_true: 'Iterable[T] | None' = None,
y_probas: 'Iterable[numbers.Number] | None' = None,
labels: 'list[str] | None' = None,
classes_to_plot: 'list[T] | None' = None,
interp_size: 'int' = 21,
title: 'str' = 'Precision-Recall Curve',
split_table: 'bool' = False
) → CustomChart
Constructs a Precision-Recall (PR) curve.
The Precision-Recall curve is particularly useful for evaluating classifiers on imbalanced datasets. A high area under the PR curve signifies both high precision (a low false positive rate) and high recall (a low false negative rate). The curve provides insights into the balance between false positives and false negatives at various threshold levels, aiding in the assessment of a model’s performance.
Args:
y_true
: True binary labels. The shape should be (num_samples
,).y_probas
: Predicted scores or probabilities for each class. These can be probability estimates, confidence scores, or non-thresholded decision values. The shape should be (num_samples
,num_classes
).labels
: Optional list of class names to replace numeric values iny_true
for easier plot interpretation. For example,labels = ['dog', 'cat', 'owl']
will replace 0 with ‘dog’, 1 with ‘cat’, and 2 with ‘owl’ in the plot. If not provided, numeric values fromy_true
will be used.classes_to_plot
: Optional list of unique class values from y_true to be included in the plot. If not specified, all unique classes in y_true will be plotted.interp_size
: Number of points to interpolate recall values. The recall values will be fixed tointerp_size
uniformly distributed points in the range [0, 1], and the precision will be interpolated accordingly.title
: Title of the plot. Defaults to “Precision-Recall Curve”.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Raises:
wandb.Error
: If NumPy, pandas, or scikit-learn is not installed.
Example:
import wandb
# Example for spam detection (binary classification)
y_true = [0, 1, 1, 0, 1] # 0 = not spam, 1 = spam
y_probas = [
[0.9, 0.1], # Predicted probabilities for the first sample (not spam)
[0.2, 0.8], # Second sample (spam), and so on
[0.1, 0.9],
[0.8, 0.2],
[0.3, 0.7],
]
labels = ["not spam", "spam"] # Optional class names for readability
with wandb.init(project="spam-detection") as run:
pr_curve = wandb.plot.pr_curve(
y_true=y_true,
y_probas=y_probas,
labels=labels,
title="Precision-Recall Curve for Spam Detection",
)
run.log({"pr-curve": pr_curve})
9 - roc_curve()
function roc_curve
roc_curve(
y_true: 'Sequence[numbers.Number]',
y_probas: 'Sequence[Sequence[float]] | None' = None,
labels: 'list[str] | None' = None,
classes_to_plot: 'list[numbers.Number] | None' = None,
title: 'str' = 'ROC Curve',
split_table: 'bool' = False
) → CustomChart
Constructs Receiver Operating Characteristic (ROC) curve chart.
Args:
y_true
: The true class labels (ground truth) for the target variable. Shape should be (num_samples,).y_probas
: The predicted probabilities or decision scores for each class. Shape should be (num_samples, num_classes).labels
: Human-readable labels corresponding to the class indices iny_true
. For example, iflabels=['dog', 'cat']
, class 0 will be displayed as ‘dog’ and class 1 as ‘cat’ in the plot. If None, the raw class indices fromy_true
will be used. Default is None.classes_to_plot
: A subset of unique class labels to include in the ROC curve. If None, all classes iny_true
will be plotted. Default is None.title
: Title of the ROC curve plot. Default is “ROC Curve”.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Raises:
wandb.Error
: If numpy, pandas, or scikit-learn are not found.
Example:
import numpy as np
import wandb
# Simulate a medical diagnosis classification problem with three diseases
n_samples = 200
n_classes = 3
# True labels: assign "Diabetes", "Hypertension", or "Heart Disease" to
# each sample
disease_labels = ["Diabetes", "Hypertension", "Heart Disease"]
# 0: Diabetes, 1: Hypertension, 2: Heart Disease
y_true = np.random.choice([0, 1, 2], size=n_samples)
# Predicted probabilities: simulate predictions, ensuring they sum to 1
# for each sample
y_probas = np.random.dirichlet(np.ones(n_classes), size=n_samples)
# Specify classes to plot (plotting all three diseases)
classes_to_plot = [0, 1, 2]
# Initialize a W&B run and log a ROC curve plot for disease classification
with wandb.init(project="medical_diagnosis") as run:
roc_plot = wandb.plot.roc_curve(
y_true=y_true,
y_probas=y_probas,
labels=disease_labels,
classes_to_plot=classes_to_plot,
title="ROC Curve for Disease Classification",
)
run.log({"roc-curve": roc_plot})
10 - scatter()
function scatter
scatter(
table: 'wandb.Table',
x: 'str',
y: 'str',
title: 'str' = '',
split_table: 'bool' = False
) → CustomChart
Constructs a scatter plot from a wandb.Table of data.
Args:
table
: The W&B Table containing the data to visualize.x
: The name of the column used for the x-axis.y
: The name of the column used for the y-axis.title
: The title of the scatter chart.split_table
: Whether the table should be split into a separate section in the W&B UI. IfTrue
, the table will be displayed in a section named “Custom Chart Tables”. Default isFalse
.
Returns:
CustomChart
: A custom chart object that can be logged to W&B. To log the chart, pass it towandb.log()
.
Example:
import math
import random
import wandb
# Simulate temperature variations at different altitudes over time
data = [
[i, random.uniform(-10, 20) - 0.005 * i + 5 * math.sin(i / 50)]
for i in range(300)
]
# Create W&B table with altitude (m) and temperature (°C) columns
table = wandb.Table(data=data, columns=["altitude (m)", "temperature (°C)"])
# Initialize W&B run and log the scatter plot
with wandb.init(project="temperature-altitude-scatter") as run:
# Create and log the scatter plot
scatter_plot = wandb.plot.scatter(
table=table,
x="altitude (m)",
y="temperature (°C)",
title="Altitude vs Temperature",
)
run.log({"altitude-temperature-scatter": scatter_plot})