Sparkline
Sparkline chart can provide an overview of data trends.
Features
- Requires only the
dataprops which is an array of numbers - You can also switch from line to a bar plot with
plotType="bar"
Props
Required Props
| Prop | Type | Description |
|---|---|---|
| id | string | Unique identifier for the component (required for Dash callbacks). |
| data | number | The data points for the sparkline (Y-values). These can be numbers or timestamps (if using d3Format for dates). |
Optional Props
| Prop | Type | Default | Description |
|---|---|---|---|
| plotType | 'line' | 'bar' | 'line' | The type of sparkline to display. |
| colorUp | string | theme.palette.success.main (Blue) | Color to use when the trend is upward (last value > first value). Uses theme.palette.success.main if not provided. |
| colorDown | string | theme.palette.error.main (Red) | Color to use when the trend is downward (last value < first value). Uses theme.palette.error.main if not provided. |
| colorFlat | string | theme.palette.grey[500] (Grey) | Color to use when the trend is flat (last value === first value or only one data point). Uses theme.palette.grey[500] if not provided. |
| sx | SxProps | undefined | Optional styles. |
| height | number | string | '100%' | Height of the chart container. For responsive charts, use a percentage value (e.g., '100%'). |
| showTooltip | boolean | false | If true, displays tooltips on data points. |
| showHighlight | boolean | false | If true, displays highlights on data points. |
| d3Format | string | undefined | Optional d3-format (for numbers on the Y-axis/main data) or d3-time-format (if Y-axis/main data are timestamps) specifier string for the Y-value displayed in tooltips. Examples: .2% (percentage), .0f (integer), %Y-%m-%d %H:%M (datetime). Refer to D3 Format and D3 Time Format for examples |
| xAxis | object | undefined | Configuration for the X-axis. Allows providing custom data points (e.g., labels, numbers, or Date objects/timestamps) and scale type. Example: { scaleType: 'time', data: [...] }. The object can contain data, scaleType, and d3Format keys. |
| yAxis | object | undefined | Configuration for the Y-axis. Example: { min: 0, max: 100 } to set a fixed Y-range. The object can contain min, max, and scaleType keys. |
Usage Examples
Here are some examples demonstrating different features of the Sparkline component. Each snippet is a self-contained Dash application that you can copy and run.
Basic Line Sparklines
This example shows basic line sparklines with different trend indications (upward, downward, and flat).
import dash
from dash import html
import yipit_dash_mui_components as dmc
app = dash.Dash(__name__)
# Set React version for compatibility if needed in your environment
# dash._dash_renderer._set_react_version("18.2.0")
# Sample Data
data_up = [1, 3, 2, 4, 5, 7, 6]
data_down = [8, 6, 7, 5, 4, 3, 2]
data_flat = [4, 4, 4, 4, 4, 4, 4]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Line Sparkline (Up Trend)"),
dmc.Sparkline(id="spark-line-up", data=data_up),
html.P(f"Data: {data_up}"),
html.Hr(),
html.H3("Line Sparkline (Down Trend)"),
dmc.Sparkline(id="spark-line-down", data=data_down),
html.P(f"Data: {data_down}"),
html.Hr(),
html.H3("Line Sparkline (Flat Trend)"),
dmc.Sparkline(id="spark-line-flat", data=data_flat),
html.P(f"Data: {data_flat}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Basic Bar Sparklines
This example demonstrates the bar plot type for sparklines.
import dash
from dash import html
import yipit_dash_mui_components as dmc
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
# Sample Data
data_up = [1, 3, 2, 4, 5, 7, 6]
data_down = [8, 6, 7, 5, 4, 3, 2]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Bar Sparkline (Up Trend)"),
dmc.Sparkline(id="spark-bar-up", data=data_up, plotType="bar"),
html.P(f"Data: {data_up}"),
html.Hr(),
html.H3("Bar Sparkline (Down Trend)"),
dmc.Sparkline(id="spark-bar-down", data=data_down, plotType="bar"),
html.P(f"Data: {data_down}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Customizing Colors
You can customize the colors for different trends (upward, downward, flat).
import dash
from dash import html
import yipit_dash_mui_components as dmc
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
# Sample Data
data_down = [8, 6, 7, 5, 4, 3, 2]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Custom Colors (Down = Blue)"),
dmc.Sparkline(id="spark-custom-color", data=data_down, colorDown="blue"),
html.P(f"Data: {data_down}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Handling Different Data Scenarios
Examples with a single data point and randomly generated data.
import dash
from dash import html
import yipit_dash_mui_components as dmc
import random
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
# Sample Data
data_single = [5]
data_random = [random.randint(0, 10) for _ in range(10)]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Single Data Point (Bar)"),
dmc.Sparkline(id="spark-single", data=data_single, plotType="bar"),
html.P(f"Data: {data_single}"),
html.Hr(),
html.H3("Random Data (Bar)"),
dmc.Sparkline(id="spark-random", data=data_random, plotType="bar"),
html.P(f"Data: {data_random}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Sizing and Layout
Demonstrates how the sparkline behaves in different sized containers.
import dash
from dash import html
import yipit_dash_mui_components as dmc
import random
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
data_random = [random.randint(0, 10) for _ in range(10)]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Inside small container (height=15px)"),
html.Div(
style={"width": "50px", "height": "30px", "border": "1px solid lightgray"},
children=[dmc.Sparkline(id="spark-small", data=data_random, height=15)]
),
html.P(f"Data: {data_random}"),
html.Hr(),
html.H3("Inside a resizable container"),
html.Div(
style={"width": "200px", "height": "100px", "resize": "both", "overflow": "auto", "border": "1px dashed gray"},
children=[dmc.Sparkline(id="spark-resizable", data=data_random, height="100%", sx={"padding": "4px"})]
),
html.P(f"Data: {data_random} (Container is resizable)"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Tooltips and Highlights
Enable tooltips and highlights for better data visibility.
import dash
from dash import html
import yipit_dash_mui_components as dmc
import random
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
data_random = [random.randint(0, 10) for _ in range(10)]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("With tooltip and highlight"),
dmc.Sparkline(
id="spark-tooltip-highlight",
data=data_random,
height=50, # Provide some height for better visibility
showTooltip=True,
showHighlight=True,
),
html.P(f"Data: {data_random}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Formatting Values (d3Format for Y-axis)
Use the d3Format prop to format numeric values displayed in tooltips.
import dash
from dash import html
import yipit_dash_mui_components as dmc
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
data_formatter = [0.1, 0.5, 0.3, 0.8, 0.4] # Data suitable for percentage
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("With numeric d3Format (percentage) for Y-values"),
dmc.Sparkline(
id="spark-numeric-d3format",
data=data_formatter,
d3Format=".0%", # Format as percentage with 0 decimal places
showTooltip=True,
height=50,
),
html.P(f"Data: {data_formatter}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Handling Empty Data
The component gracefully handles empty datasets by rendering nothing.
import dash
from dash import html
import yipit_dash_mui_components as dmc
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
data_empty = []
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Empty Data (renders nothing)"),
dmc.Sparkline(id="spark-empty", data=data_empty, height=50),
html.P(f"Data: {data_empty}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Configuring the X-Axis
Examples of providing custom labels or time-series data for the X-axis.
X-Axis with String Labels
You can provide string labels for the X-axis data points.
import dash
from dash import html
import yipit_dash_mui_components as dmc
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
data_up = [1, 3, 2, 4, 5, 7, 6]
x_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("With xAxis string labels"),
dmc.Sparkline(
id="spark-xaxis-labels",
data=data_up, # Y-values
xAxis={"data": x_labels}, # X-values (labels)
showTooltip=True,
height=50,
),
html.P(f"Y-Data: {data_up}, X-Labels: {x_labels}"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
X-Axis with Time Data and Formatting
Use scaleType: 'time' for time-series data on the X-axis and format tooltip values using d3Format.
import dash
from dash import html
import yipit_dash_mui_components as dmc
import random
from datetime import datetime, timezone, timedelta
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
# Sample time-series data for X-axis (timestamps in milliseconds)
base_date = datetime(2023, 1, 1, tzinfo=timezone.utc)
data_timestamps_x_varied = [
(base_date + timedelta(days=i*2)).timestamp() * 1000 for i in range(8)
]
# Corresponding Y-values
data_for_varied_x = [random.randint(0, 10) for _ in range(len(data_timestamps_x_varied))]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("With xAxis time data & d3Format"),
dmc.Sparkline(
id="spark-xaxis-time",
data=data_for_varied_x, # Y data
xAxis={
"scaleType": "time",
"data": data_timestamps_x_varied, # X data (timestamps)
"d3Format": "%Y-%m-%d", # Format for X-axis tooltip
},
showTooltip=True,
showHighlight=True,
height=50,
),
html.P(f"Y-Data: {data_for_varied_x}, X-Data: Timestamps formatted as YYYY-MM-DD"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Configuring the Y-Axis
Set a fixed range for the Y-axis using the yAxis prop.
import dash
from dash import html
import yipit_dash_mui_components as dmc
import random
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
data_random = [random.randint(0, 10) for _ in range(10)] # Values between 0-10
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("With yAxis fixed range [0-50]"),
dmc.Sparkline(
id="spark-yaxis-range",
data=data_random,
yAxis={"min": 0, "max": 50}, # Data will appear in the lower part
plotType="bar",
height=50,
showHighlight=True,
showTooltip=True,
),
html.P(f"Data: {data_random} (Y-Axis Range: 0-50)"),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Advanced Formatting: Y-Values as Timestamps
If your main data prop contains timestamps (e.g., durations), you can format them in tooltips using d3Format.
import dash
from dash import html
import yipit_dash_mui_components as dmc
from datetime import datetime, timezone, timedelta
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
# Y-values as timestamps (e.g., duration in milliseconds)
now_ms = datetime.now(timezone.utc).timestamp() * 1000
data_timestamps_y = [now_ms + i * 60000 for i in range(5)] # Timestamps in ms, 1 min apart
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("With d3Format for Y-value timestamps"),
dmc.Sparkline(
id="spark-d3format-time-y",
data=data_timestamps_y, # Y-values are timestamps
d3Format="%H:%M:%S", # Format as HH:MM:SS
showTooltip=True,
height=50,
),
html.P("Y-Data consists of timestamps, formatted to HH:MM:SS in tooltips."),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Complex Example: Time-based X-Axis and Formatted Numeric Y-Axis
This example combines a time-based X-axis (with its own formatting) and numeric Y-values that are also formatted using d3Format.
import dash
from dash import html
import yipit_dash_mui_components as dmc
import random
from datetime import datetime, timezone, timedelta
app = dash.Dash(__name__)
# dash._dash_renderer._set_react_version("18.2.0")
# X-values as timestamps
base_date = datetime(2023, 1, 1, tzinfo=timezone.utc)
data_timestamps_x = [(base_date + timedelta(days=i)).timestamp() * 1000 for i in range(8)]
# Numeric Y-values (e.g., large numbers)
data_numeric_y = [random.randint(1000, 5000) for _ in range(len(data_timestamps_x))]
app.layout = dmc.YipitMUIProvider(
children=[
html.H3("Time X-Axis & Formatted Numeric Y-Axis"),
dmc.Sparkline(
id="spark-xaxis-time-y-numeric-format",
data=data_numeric_y, # Numeric data for Y
xAxis={
"scaleType": "time",
"data": data_timestamps_x,
"d3Format": "%b %d, %Y", # Format for X-axis tooltip: Jan 01, 2023
},
d3Format=",.0f", # Format Y-value as integer with comma for thousands
showTooltip=True,
height=60,
showHighlight=True,
),
html.P("X-axis shows time, Y-axis shows large numbers formatted with commas."),
]
)
if __name__ == "__main__":
app.run_server(debug=True)
Best Practices
- Always provide unique
idprops when using multiple Sparkline components in the same Dash application to ensure callbacks and state work correctly. - For time-series data on the X-axis, ensure your
dataforxAxisare timestamps (milliseconds since epoch) orDateobjects and setscaleType: 'time'. - Use
d3Formatfor formatting tooltip values, referring to d3-format and d3-time-format documentation for specifiers. - When
heightis a percentage, ensure the parent container has a defined height for the sparkline to render correctly.