Skip to content
opencorPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

OpenCOR Plot

@opencor/plot is a Vue 3 component for plotting data. It is used by OpenCOR, but it can be used by any Vue 3 application.

Try it out in our demo app, e.g., with millions of points, live data, or several plots whose axes are aligned and synchronised.

Key characteristics:

Contents:

Installation

bun add @opencor/plot  # Or npm install @opencor/plot, etc.

Vue 3 is a peer dependency. uPlot is our only other runtime dependency and gets installed along with @opencor/plot.

Usage

<template>
  <div style="height: 640px">
    <OpenCORPlot :data="data" />
  </div>
</template>

<script setup lang="ts">
import OpenCORPlot, { type PlotData } from '@opencor/plot';
import '@opencor/plot/style.css';

const x = Float64Array.from({ length: 1000 }, (_, i) => i / 100);

const data: PlotData = {
  xAxis: { title: 'Time (s)' },
  yAxis: { title: 'Voltage (mV)' },
  traces: [
    {
      name: 'V',
      xValue: 'time',
      x,
      yValue: 'membrane.V',
      y: x.map((t) => Math.sin(t))
    }
  ]
};
</script>

The component fills its container, so the container must have a height. @opencor/plot/style.css contains all the CSS that is needed, including uPlot's.

Types

The component is the default export of @opencor/plot, and is also exported as OpenCORPlot. These types are exported too:

Type Definition Description
PlotData { traces, title?, titlePosition?, xAxis?, yAxis? } The data to plot (see Data).
PlotTitlePosition 'top' | 'left' | 'right' | 'bottom' Where the title of the plot is (see Data).
PlotAxis { title?, range?, grid?, log? } An axis of the plot (see Data).
PlotTrace { name, x, y, xValue, yValue, line?, marker?, traceId?, legendRank?, runLabel? } A trace to plot (see Data).
PlotLineStyle { type?, color?, thickness? } The style of the line of a trace (see Data).
PlotLineType 'none' | 'solid' | 'dash' | 'dot' | 'dashDot' | 'dashDotDot' The type of the line of a trace (see Data).
PlotMarkerStyle { type?, size?, fill?, lineColor?, lineThickness? } The style of the markers of a trace (see Data).
PlotMarkerType 'none' | 'square' | 'circle' | 'diamond' | 'xCross' | 'plus' | 'star' | 'triangleUp' | 'triangleDown' | 'triangleLeft' | 'triangleRight' | 'hDash' | 'vDash' The type of the markers of a trace (see Data).
PlotTheme 'system' | 'light' | 'dark' The value of the theme prop.
PlotGroup string | symbol A group of plots, i.e. the value of the xAxisAlign, xAxisSync, yAxisAlign, and yAxisSync props. A symbol is unique, so that unrelated parts of a page can't end up in the same group by using the same string.
PlotAxesSettings { x: PlotAxisSettings; y: PlotAxisSettings } The payload of the axesUpdated event, i.e. the current settings of the axes, which the user can change using the context menu, so that the data can say the same (see PlotAxis).
PlotAxisSettings { grid: boolean; log: boolean } The settings of an axis: whether its grid lines are shown and whether it is logarithmic.
PlotRanges { x: [number, number]; y: [number, number]; zoomed: { x: boolean; y: boolean } } The payload of the rangesUpdated event, i.e. the current ranges of the axes (in actual units, even along a logarithmic axis) and whether each axis is zoomed (rather than autoranged). To restore them later, give { x: zoomed.x ? x : null, y: zoomed.y ? y : null } to setRanges(), so that an autoranged axis stays autoranged.
PlotRangesToSet { x?: [number, number] | null; y?: [number, number] | null } The ranges to give to setRanges(), i.e. the range (in actual units, even along a logarithmic axis) into which to zoom an axis, null to reset the zoom of an axis, or nothing to leave an axis as it is.
PlotCsvExportEvent PlotCsvExportStartedEvent | PlotCsvExportProgressEvent | PlotCsvExportFinishedEvent The payload of the csvExport event. Use its type to tell which one it is.
PlotCsvExportStartedEvent { type: 'started' } An export to CSV has started.
PlotCsvExportProgressEvent { type: 'progress'; percent: number } An export to CSV has made some progress: percent goes from 0 to 100 (an integer).
PlotCsvExportFinishedEvent { type: 'finished'; success: boolean } An export to CSV has finished, whether successfully (and the file was downloaded) or not.
PlotImageExportEvent { action: 'copy' | 'export'; format: 'jpeg' | 'png' | 'svg' | 'webp'; success: boolean } The payload of the imageExport event: whether the plot was copied to the clipboard (always as PNG) or exported to an image file, in which format, and whether it worked.
PlotContextMenuEvent { clientX: number; clientY: number; usingKeyboard: boolean; items: ContextMenuItem[] } The payload of the contextMenu event: where the context menu was requested (in client coordinates), whether it was requested using the keyboard (in which case the custom menu should take the keyboard focus), and the items that our context menu would have shown. These items reflect the plot as it was when the context menu was requested and don't get updated if the data changes while the custom context menu is shown, but their commands always act on the plot as it is when they are chosen.
ContextMenuItem ContextMenuAction | ContextMenuSeparator | ContextMenuHeader An item of a context menu.
ContextMenuAction { id?: string; label: string; icon?: IconName; checked?: boolean; disabled?: boolean; command?: () => void; items?: ContextMenuItem[] } An action: its id (so that it can be found, see Context menu items), its label, its icon, whether it is checked (only for a checkable action, e.g., to make an axis logarithmic), whether it is disabled (i.e. greyed out, can't be chosen, and its submenu, if any, can't be opened, although it can still be focused, so that assistive technologies announce it as disabled, and it still shows whether it is checked), the command to call when it is chosen, and its submenu items, if any.
ContextMenuSeparator { separator: true } A separator.
ContextMenuHeader { header: string } A header that can't be chosen, e.g., the full name of a trace when the context menu is requested from its legend item. It can contain a little HTML (see Data).
IconName 'angle-right' | 'arrows-h' | 'arrows-v' | 'chart-line' | 'check' | 'copy' | 'download' | 'eye' | 'image' | 'list' | 'pencil' | 'refresh' | 'search-minus' | 'search-plus' The name of an icon (from PrimeIcons).
PlotPointCounts { nbOfPoints: number; nbOfDrawnPoints: number } The value returned by the pointCounts() method.
PlotMemoryUsage { levelOfDetail: number; logValues: number } The value returned by the memoryUsage() method.

Data

PlotData:

Property Type Description
traces PlotTrace[] The traces to plot.
title string The title of the plot.
titlePosition PlotTitlePosition Where the title of the plot is: above the plot ('top', the default) or below it ('bottom'), centred on its plotting area, or to its left ('left'), centred on its plotting area and reading from bottom to top (like the title of the Y axis), or to its right ('right', i.e. between its plotting area and its legend), centred on its plotting area and reading from top to bottom.
xAxis, yAxis PlotAxis The axes.

PlotAxis:

Property Type Description
title string The title of the axis.
range [number | null, number | null] The range of the axis when the zoom is reset. By default, it fits the data. An end that is null (or that can't be plotted, e.g., a non-positive end along a logarithmic axis) fits the data, while the other end is kept (e.g., [0, null] for an axis that starts at 0). If there is no data to fit or it is all beyond the end that is kept, then the axis extends from that end by 1 or 1ppm of it, whichever is bigger.
grid boolean Whether to show the grid lines along the axis, i.e. the vertical grid lines for the X axis and the horizontal grid lines for the Y axis. It is used when the plot is created and whenever it changes. In between, the user can still show or hide the grid lines using the context menu, even while the data gets updated (handle the axesUpdated event to keep the data in sync). By default, the grid lines are shown. The zero line of the axis, if any, is always shown.
log boolean Whether the axis is logarithmic. It is used when the plot is created (unless the plot joins a synchronisation group that already has some plots, in which case it takes on the scale of the group) and whenever it changes (in which case the plots of the synchronisation group of the axis, if any, do the same, as if the user had made the axis logarithmic, or not, using the context menu). In between, the user can still make the axis logarithmic, or not, using the context menu, even while the data gets updated (handle the axesUpdated event to keep the data in sync). By default, the axis is linear.

PlotTrace:

Property Type Description
name string The name of the trace, as shown in the legend, the hover tooltip, and the CSV export.
x, y Float64Array The X and Y values of the trace.
xValue, yValue string What the X and Y values are (e.g., the name of a model variable), used in the CSV export.
line PlotLineStyle The optional style of the line of the trace, which also gives the default colour of its markers (see below).
marker PlotMarkerStyle The optional style of the markers of the trace (see below). Without it, the trace has circle markers if it has fewer than 20 points, and no markers otherwise.
traceId string An optional identifier that keeps the visibility of the trace when the data is updated. Otherwise, the trace is identified by its name, xValue, yValue, and runLabel (and, among traces that have the same ones, by their order), or by its position if it doesn't have a name, xValue, and yValue.
legendRank number The optional rank of the trace in the legend (lower ranks first, 1000 by default).
runLabel string An optional label that tells apart the X column of the trace from those of other runs in the CSV export.

PlotLineStyle:

Property Type Description
type PlotLineType The type of the line: no line at all ('none'), a solid line ('solid', the default), or a dashed line, with dashes ('dash'), dots ('dot'), dashes and dots ('dashDot'), or dashes and pairs of dots ('dashDotDot'). The dashes, dots, and gaps of a dashed line are 4, 1, and 2 times its thickness (or 8, 2, and 4 pixels if it is less than 2 pixels thick, so that it still looks dashed).
color string The colour of the line (and, by default, of the markers of its trace), as a CSS colour, which can be transparent (e.g., '#1f77b4', '#1f77b480', or 'rgba(31, 119, 180, 0.5)'). By default, it is one of Tableau 10's colours, based on the position of its trace in traces, i.e. '#4e79a7' (blue), '#f28e2b' (orange), '#e15759' (red), '#76b7b2' (teal), '#59a14f' (green), '#edc948' (yellow), '#b07aa1' (purple), '#ff9da7' (pink), '#9c755f' (brown), '#bab0ac' (grey), and then '#4e79a7' again, etc.
thickness number The thickness of the line, in pixels (2 by default).

For example, a dashed red line that is 3 pixels thick and half transparent:

const trace: PlotTrace = {
  name: 'Membrane potential',
  xValue: 'time',
  x,
  yValue: 'V',
  y,
  line: { type: 'dash', thickness: 3, color: 'rgba(214, 39, 40, 0.5)' }
};

The style of a line is used wherever its trace is drawn: the plot, its legend and hover tooltip (whose swatches show a dashed line with a dash pattern of its own, which fits in them, so that it can be told apart from others), its hover points, its live point, and its copied and exported images (including SVG, where a transparent colour uses an opacity attribute, since SVG 1.1 has no transparent colours).

PlotMarkerStyle:

Property Type Description
type PlotMarkerType The type of the markers: no markers at all ('none'), a square ('square'), a circle ('circle', the default), a diamond ('diamond'), an X cross ('xCross'), a plus ('plus'), a star ('star', i.e. a plus and an X cross), a triangle that points up ('triangleUp'), down ('triangleDown'), left ('triangleLeft'), or right ('triangleRight'), or a horizontal ('hDash') or vertical ('vDash') dash.
size number The size of the markers, in pixels (6 by default), i.e. the width and height of the square in which the shape of a marker fits, outline excluded (like Plotly).
fill string The colour inside the markers, as a CSS colour, which can be transparent (e.g., 'transparent' for hollow markers). By default, it is the colour of the line of the trace. An X cross, a plus, a star, and a dash have no inside, so they have no fill.
lineColor string The colour of the outline of the markers (or of the lines of an X cross, a plus, a star, or a dash), as a CSS colour, which can be transparent. By default, it is the colour of the line of the trace.
lineThickness number The thickness of the outline of the markers (or of the lines of an X cross, a plus, a star, or a dash), in pixels (1 by default, or 0 if the outline has the same colour as the fill, as it does by default, since it would then only make the markers look bigger). An outline is centred on the edge of the shape of a marker, so it makes it look bigger by its thickness (e.g., 7 pixels for a 6-pixel marker with a 1-pixel outline). It can be 0 for markers that only have a fill.

For example, hollow red diamonds that are 10 pixels big, without a line:

const trace: PlotTrace = {
  name: 'Measurements',
  xValue: 'time',
  x,
  yValue: 'V',
  y,
  line: { type: 'none' },
  marker: { type: 'diamond', size: 10, fill: 'transparent', lineColor: '#d62728', lineThickness: 2 }
};

Giving a marker style, even an empty one (i.e. marker: {}), means that the trace has markers whatever its number of points, and type: 'none' means that it has no markers at all. A marker which fill and outline have the same colour (as they do by default) and which has an outline is drawn as one filled shape, including its outline, so that it looks the same, even if that colour is transparent (rather than its outline showing over its fill). Markers are drawn one by one, so a marker covers those drawn before it, and transparent markers get darker where they overlap. A trace with many points gets at most one marker per pixel (since more markers would look the same, but would be slower to draw). The axes get padded so that the markers of the points at the end of an axis are fully shown (by an amount that depends on their size and on the thickness of their outline).

Like the line of a trace, its markers are used wherever its trace is drawn: the plot, its legend and hover tooltip (whose swatches show its line, if any, and its marker, if any, up to 10 pixels big), its hover points (which are its marker, a third bigger, and at least 8 pixels big), and its copied and exported images (including SVG). A trace that has neither a line nor markers is not drawn at all, and it is not listed in the legend or the hover tooltip (but it is still exported to CSV).

A dashed line is dashed along the path that is actually drawn, which goes through up to four points per pixel column (see Large and live data). So, a dense trace (e.g., noisy data) looks solid, like a solid line would, since its pixel columns are drawn as vertical segments. Its dash pattern also starts again where the trace comes back into the plotting area (e.g., when zoomed in) or carries on after a gap.

Notes:

  • Titles and trace names can contain a little HTML (b, br, code, em, i, strong, sub, and sup). Anything else is removed.
  • A trace can be a function of X (e.g., against time) or not (e.g., a phase plot). A point with a non-finite X or Y value (e.g., NaN) is a gap in its trace.
  • A trace with fewer than 20 points also has circle markers, unless it has a marker style.

Large and live data

The component only goes through the points that are needed for a trace to look the same, and draws it using only as many segments as are needed for it to look the same (within a quarter of a canvas pixel), so a trace with millions of points can be zoomed, panned, and hovered smoothly.

The data is updated by giving the component a new data object, since changes made to an existing data object (e.g., to its traces array or to one of its traces) are not watched.

When the data is updated, the work that has already been done is reused if the new values of a trace are a continuation of its previous ones, i.e. a view of the same buffer, from the same offset, and at least as long. Only the new values (and the last of the previous values, which may have changed) then get processed. The very same arrays (i.e. not new views) are assumed not to have changed at all. So, for live data (e.g., while a simulation is running), allocate a buffer for all the values, fill it as values become available, and give the component a view of the part that is filled:

const xBuffer = new Float64Array(nbOfPoints);
const yBuffer = new Float64Array(nbOfPoints);

// Each time some new values have been added to the buffers:

data.value = {
  ...data.value,
  traces: [{ ...trace, x: xBuffer.subarray(0, nbOfValues), y: yBuffer.subarray(0, nbOfValues) }]
};

Also set the live prop while the data is live, so that the last point of each visible trace gets marked, making its latest value easy to spot (even where a trace overlaps itself, e.g., in a phase plot).

Several plots

Plots can be shown together (e.g., stacked or side by side) and made to work as one, using a PlotGroup, i.e. a string or a symbol, which all the plots of a group share:

  • Aligned axes: the plots of an xAxisAlign group get the same left and right margins, so that their plotting areas line up when they are stacked, while those of a yAxisAlign group get the same top and bottom margins, so that their plotting areas line up when they are side by side. This is also the case if some of them have a title and others don't, or if their titles are at different positions. In that case, a plot leaves room for the title of the plots that have one on the left (or right), so that its Y axis title (or legend) lines up with theirs.
  • Synchronised axes: the plots of an xAxisSync (or yAxisSync) group share the range and the scale (i.e. linear or logarithmic) of their X (or Y) axis. Zooming, panning, or resetting the zoom of one of them, or making its axis logarithmic (or not), does the same to the others, be it done by the user or using setRanges(). Until one of them gets zoomed or panned, their axes fit the data of all of them. With a synchronised X axis, hovering one of them also shows the hover guide and tooltip of the others, at the same X value (or, for a plot that has no point there, at its closest point, as when it is hovered itself).

Aligning and synchronising are independent of each other: plots can be aligned without being synchronised (e.g., when they show different X values), and synchronised without being aligned (e.g., when they are not shown next to each other). A plot can also be in different groups for its X and Y axes, and the groups of X axes are separate from those of Y axes, so the same group can be used for both.

For example, to stack a plot of the membrane potential of a cell and a plot of its membrane current, both against time, with their plotting areas lined up and, unless the user unchecks a checkbox, zooming or panning the time axis of one plot doing the same to the other:

<template>
  <label><input v-model="linked" type="checkbox" /> Linked time axes</label>
  <div style="height: 320px">
    <OpenCORPlot :data="voltageData" :xAxisAlign="TIME" :xAxisSync="linked ? TIME : undefined" />
  </div>
  <div style="height: 320px">
    <OpenCORPlot :data="currentData" :xAxisAlign="TIME" :xAxisSync="linked ? TIME : undefined" />
  </div>
</template>

<script setup lang="ts">
import OpenCORPlot, { type PlotData } from '@opencor/plot';
import '@opencor/plot/style.css';

import { ref } from 'vue';

const TIME = Symbol('time');

const linked = ref(true);
const t = Float64Array.from({ length: 1000 }, (_, i) => i / 100);

const voltageData: PlotData = {
  xAxis: { title: 'Time (s)' },
  yAxis: { title: 'Voltage (mV)' },
  traces: [
    {
      name: 'V',
      xValue: 'time',
      x: t,
      yValue: 'membrane.V',
      y: t.map((time) => 50 * Math.sin(time) - 30)
    }
  ]
};

const currentData: PlotData = {
  xAxis: { title: 'Time (s)' },
  yAxis: { title: 'Current (µA/cm²)' },
  traces: [
    {
      name: 'I',
      xValue: 'time',
      x: t,
      yValue: 'membrane.I',
      y: t.map((time) => 2000 * Math.cos(time)),
      line: { color: '#e15759' }
    }
  ]
};
</script>

Here, the plotting areas line up even though the Y axis of the current plot needs more room for its tick labels (e.g., -2000 rather than -80). Both plots show the same 10 seconds, and hovering one of them also shows the values of the other at the same time.

A symbol is unique, so that unrelated parts of a page can't end up in the same group by using the same string. A plot joins or leaves a group whenever its props change (e.g., to let the user choose whether some plots are synchronised), and leaves its groups when it is unmounted. A plot that joins a group with a synchronised axis takes on the range and scale of that axis (even if its data says that the axis is logarithmic, or not, see PlotAxis), unless it is the first plot of the group.

To keep track of the ranges of the axes of a plot (e.g., to restore them later), handle its rangesUpdated event.

Props

Prop Type Default Description
data PlotData (required) The data to plot.
showLegend boolean true Whether to show the legend. The legend takes at most 40% of the width of the plot (with long trace names truncated, and shown in full when hovered or in the context menu of their legend item), and is hidden if the plot is too narrow for it to be useful. It is used when the plot is created and whenever it changes. In between, the user can still show or hide the legend using the context menu (use v-model:showLegend to keep it in sync).
theme PlotTheme 'system' Whether to use light or dark mode, or whatever the system uses.
xAxisAlign PlotGroup The group of plots whose X axes are to line up with this plot's, i.e. whose plotting areas are to have the same left and right edges (e.g., when they are stacked).
xAxisSync PlotGroup The group of plots whose X axis is to be synchronised with this plot's, i.e. which share the range and the scale of their X axis, so that zooming, panning, or resetting the zoom of one of them does the same to the others, as does making its X axis logarithmic (or not). Their X axes always show the same range, which, until one of them gets zoomed or panned, fits the data of all of them. Hovering one of them also shows the hover guide and tooltip of the others at the same X value (next to their guide line, at the same relative height as the mouse pointer or finger), so that the values of all of them can be read at once. Like the hovered plot, a plot that has no point at that X value shows its closest point instead, so that its guide line goes through its highlighted points and its tooltip shows the X value of its values. For a trace whose X values are not sorted (e.g., a phase plot), the others show the point that is closest to where the mouse pointer would be, i.e. at their guide line and at that relative height, if any is close enough to it.
yAxisAlign PlotGroup The group of plots whose Y axes are to line up with this plot's, i.e. whose plotting areas are to have the same top and bottom edges (e.g., when they are side by side).
yAxisSync PlotGroup The group of plots whose Y axis is to be synchronised with this plot's, i.e. which share the range and the scale of their Y axis, so that zooming, panning, or resetting the zoom of one of them does the same to the others, as does making its Y axis logarithmic (or not). Their Y axes always show the same range, which, until one of them gets zoomed or panned, fits the data of all of them.
appendTo HTMLElement | string body Where to append our overlays (context menu, hover tooltip, etc.).
customContextMenu boolean false Whether to emit a contextMenu event rather than show our own context menu. To have no context menu at all, set it and don't handle the contextMenu event.
contextMenuItems (items: ContextMenuItem[]) => ContextMenuItem[] A function that customises the items of the context menu, i.e. that is given the plot's items (a new array each time) and returns the items to show, e.g., to add an item that lets the user choose whether the X axis of the plot is synchronised with that of other plots (by setting the xAxisSync prop accordingly). It gets called whenever the items are built (e.g., when the context menu is requested), so the items that it adds can reflect the current state of the app (e.g., whether an item is checked). Its items are also the items of the contextMenu event. The plot's actions have an id (see ContextMenuAction), so that they can be found whatever their label (see Context menu items).
levelOfDetail boolean true Whether to only go through the points that are needed for a trace to look the same when drawing it (see Large and live data). Hovering a trace whose X values are sorted always does. Only meant to be disabled to see how much it helps.
live boolean false Whether the data is live (e.g., while a simulation is running), in which case the last point of each visible trace is marked.

To draw traces without our level of detail, use :levelOfDetail="false". Our path builder then goes through every point of every trace (still only drawing the first, minimum, maximum, and last points of each pixel column, so that a trace looks the same) and draws all of those points (rather than only as many as are needed for a trace to look the same). Unlike uPlot's own, our path builder handles gaps (e.g., NaN values) and traces whose X values are not sorted (e.g., phase plots) at any number of points (splitting a path of more than 1,000,000 points into several paths, since Chrome draws nothing for a path of more than about 1,870,000 points), and in Firefox, it splits a path of more than 2,000 points into several paths, since Firefox only strokes a path quickly if it has no more than a few thousand points. This is also the reference that our optimisations can be benchmarked against.

Events

Event Payload Description
axesUpdated PlotAxesSettings Whether an axis has its grid lines shown or is logarithmic has changed, e.g., because the user changed it using the context menu, or because the plot joined a synchronisation group whose axis has another scale. It is not emitted when the plot is created. Handle it to keep the data in sync (see PlotAxis).
csvExport PlotCsvExportEvent An export to CSV has 'started', made 'progress' (with a percent), or 'finished' (with whether it was a success), so that its progress can be shown.
imageExport PlotImageExportEvent The plot has been copied to the clipboard or exported to an image (or has failed to be), so that the user can be told about it.
rangesUpdated PlotRanges The range of an axis has changed, or whether it is zoomed has. It is emitted at most once per frame, including while the plot is being zoomed, panned, or animated, and while its data gets updated.
update:showLegend boolean The user has shown or hidden the legend using the context menu, so that the showLegend prop can say the same (e.g., using v-model:showLegend).
contextMenu PlotContextMenuEvent Only with customContextMenu: the context menu was requested at clientX/clientY, with the items that our context menu would have shown. The custom menu should show the actions that are disabled (see ContextMenuAction) as such, and not let them (or their submenu items) be chosen. If usingKeyboard is true, the custom menu should take the keyboard focus. The custom menu should call the command of the chosen item while handling the click (or tap, or key press) that chose it, and it shouldn't move the keyboard focus afterwards (calling contextMenuHidden() instead), since some commands (e.g., to edit the range of an axis) give the keyboard focus to an editor that closes when it loses it, and iOS only shows its virtual keyboard for such an editor while handling a user interaction. If it calls that command while handling a key press (e.g., Enter or Space), it should also prevent that key's default action (using preventDefault()), since the key would otherwise also be typed into such an editor, replacing its selected value.

Methods

Available through a template ref:

Method Description
contextMenuHidden() Tell the plot that a custom context menu (see contextMenu) has been hidden, so that it can get the keyboard focus back (unless something else, e.g., an editor opened by the chosen item, has it).
setRanges(ranges, options?) Zoom the axes into the given ranges and/or reset their zoom (see PlotRangesToSet), as if the user had done it (so, a synchronised axis gets updated in all the plots of its group), animating the change if options.animate is set (false by default). A range that can't be plotted (e.g., with a non-positive end along a logarithmic axis, or with two ends that are the same) is ignored.
pointCounts() The number of points of the visible traces (nbOfPoints), and how many of them were last drawn (nbOfDrawnPoints), as a PlotPointCounts. Meant for testing and benchmarking.
memoryUsage() The memory (in bytes) used by the component itself, not counting the data, as a PlotMemoryUsage: by its levels of detail (levelOfDetail) and by the logarithm of its values along logarithmic axes (logValues). Meant for testing and benchmarking.

Interaction

Like with Plotly:

  • Plotting area: drag to zoom (along one axis if the drag is mostly horizontal or vertical), Shift+drag to pan, use the mouse wheel to zoom around the mouse pointer, and double-click to reset the zoom.
  • Middle of an axis: drag to pan along that axis, use the mouse wheel to zoom along it, and double-click to reset its zoom.
  • Ends of an axis and bottom corners: drag to move an end of the axis, or click an end of the axis to type its value.
  • Legend: click a trace to show or hide it, double-click it to only show that trace (or all the traces again), and hover it to highlight its trace. Its context menu (right-click, or Shift+F10 once it has the focus) can also show only that trace (or all the traces again), or show or hide it if it is the only trace.
  • Touch (or a pen): on the plotting area, swipe to scroll the page, use two fingers to zoom and pan, touch and hold, then drag to zoom (in browsers that don't turn a pen into touch events, e.g., Chrome on Windows, a pen doesn't scroll the page, but drags to zoom straight away, as a mouse does), and tap, then drag straight away to move the hover tooltip (which is shown above the finger). On the axes, drag with one finger as with a mouse. Tap and double-tap as you would click and double-click. Touch and hold, then release, to open the context menu (as with a right-click), including from a legend item. If a touchscreen is available, the axes can be dragged a bit further away from the plotting area, the ends of the axes are longer, and the legend items and context menu items are taller.
  • Keyboard (once the plot has the focus): + and − to zoom in and out, 0 to reset the zoom, the arrow keys to pan, and Shift+F10 (or the context menu key) to open the context menu (e.g., to type the value of an end of an axis). Each legend item can also get the focus: Enter or Space shows or hides its trace, and Shift+F10 opens its context menu.
  • Escape, or pressing another mouse button, cancels a drag.

Hovering shows the value of each visible trace at the X value under the mouse pointer. For a trace that is not a function of X (e.g., a phase plot), it shows the point closest to the mouse pointer instead.

With synchronised axes (see Several plots), zooming, panning, resetting the zoom, editing the range of an axis, and making an axis logarithmic (or not) apply to all the plots of the group of that axis, be it done with the mouse, by touch, with the keyboard, or from the context menu.

The context menu can zoom in and out, reset the zoom, show or hide the legend, edit the range of an axis, show or hide its grid lines, and make it logarithmic (from the submenu of that axis), copy the plot to the clipboard, export it as JPEG, PNG, SVG, or WebP, and export its data to CSV, and an app can customise it (see contextMenuItems). When requested from a legend item, it can also show only that trace (or all the traces again), or show or hide it if it is the only trace.

Copied and exported images always use the light colours (white background, dark text), whatever the current theme, since they are typically used in light documents.

Context menu items

The items of the context menu can be customised using the contextMenuItems prop, e.g., to add an item that lets the user choose whether the X axes of some plots are synchronised, at the end of the submenu of the X axis (and separated from its other items), and which is disabled when there is no other plot to synchronise with:

import { type ContextMenuAction, type ContextMenuItem } from '@opencor/plot';

import { ref } from 'vue';

// The number of plots, which the app must keep up to date (e.g., using a computed from its list of plots), so that our
// item gets disabled when there is no other plot to synchronise with.

const nbOfPlots = ref(2);
const linkedXAxes = ref(true);

const contextMenuItems = (items: ContextMenuItem[]): ContextMenuItem[] => {
  const xAxisItem = items.find((item): item is ContextMenuAction => 'id' in item && item.id === 'xAxis');

  xAxisItem?.items?.push(
    {
      separator: true
    },
    {
      label: 'Linked',
      checked: linkedXAxes.value,
      disabled: nbOfPlots.value < 2,
      command: () => {
        // Note: the items don't get updated while a custom context menu (see customContextMenu) is shown, so this item
        //       may still be chosen after the number of plots has dropped to one, hence we check it again.

        if (nbOfPlots.value < 2) {
          return;
        }

        linkedXAxes.value = !linkedXAxes.value;
      }
    }
  );

  return items;
};

The plot's actions have an id, so that they can be found whatever their label:

ID Action
traceVisibility Show only a trace (or all the traces again), or show or hide it if it is the only trace (only when the context menu is requested from a legend item, after a header with the name of its trace).
zoomIn, zoomOut Zoom in and out.
resetZoom Reset the zoom.
legend Show or hide the legend.
xAxis, yAxis The submenu of an axis, with the items below.
xAxisMinimum, xAxisMaximum, yAxisMinimum, yAxisMaximum Edit the minimum or maximum of an axis.
xGridLines, yGridLines Show or hide the grid lines along an axis.
logarithmicXAxis, logarithmicYAxis Make an axis logarithmic (or not).
copyToClipboard Copy the plot to the clipboard.
exportPlot Export the plot, with exportPlotAsJpeg, exportPlotAsPng, exportPlotAsSvg, and exportPlotAsWebp in its submenu.
exportDataToCsv Export the data to CSV.

Theming

Set any of these CSS variables on an ancestor of the component. Each has a light and a dark default, based on PrimeVue's Aura theme. They don't affect copied and exported images, which always use the light defaults:

Variable Used for
--opencor-plot-background The background of the plot.
--opencor-plot-text-color The plot and axis titles, the legend, and the ring around the last point of a live trace.
--opencor-plot-muted-text-color Tick labels, the hover guide line, hidden traces in the legend, and secondary text in overlays.
--opencor-plot-primary-color The zoom box (and, by default, the keyboard focus ring).
--opencor-plot-grid-color Grid lines.
--opencor-plot-zero-line-color The zero lines.
--opencor-plot-hidden-trace-color The legend swatch of a hidden trace.
--opencor-plot-hover-background Hovered items (e.g., in the legend and context menu).
--opencor-plot-overlay-background The background of the context menu and hover tooltip.
--opencor-plot-overlay-border-color Their border.
--opencor-plot-overlay-text-color Their text.
--opencor-plot-overlay-shadow Their shadow.
--opencor-plot-border-radius Rounded corners.
--opencor-plot-focus-ring-width The width of the keyboard focus ring.
--opencor-plot-focus-ring-color The colour of the keyboard focus ring (the primary colour by default).

Development

Bun is required.

bun install          # Install the dependencies.
bun run build        # Build the library.
bun dev              # Run the demo app.
bun build:demo       # Build the demo app.
bun format           # Format the code.
bun format:check     # Check the code formatting (without fixing it).
bun lint             # Lint the code.
bun lint:check       # Lint the code (without fixing it).
bun test             # Run the tests.
bun test --coverage  # Run the tests with code coverage.
bun test --watch     # Run the tests in watch mode.
bun typecheck        # Type check the code.
bun clean            # Remove all generated files.
bun benchmark            # Benchmark the plot (see below).
bun dependencies:update  # Check for and update outdated dependencies.
bun version:new          # Bump the version number.

Our demo app gets deployed to GitHub Pages whenever main gets updated (see our demo workflow).

Benchmarking

bun benchmark builds the demo app, serves it, and runs its benchmark (i.e. what the Run benchmark button of its Benchmark section does) in one or more browsers, for a set of scenarios. Its results get saved as a report in benchmark-results/, named after when the benchmark was run, as HTML (to be opened in a browser), Markdown (e.g., to be pasted in an issue), and JSON (e.g., to be compared with other results). The report is updated as results come in, so it is there even if the benchmark gets interrupted.

bun benchmark                                       # All the browsers and scenarios.
bun benchmark --browsers chrome                     # Only Chrome.
bun benchmark --scenarios noisy-3x1m,unsorted-3x1m  # Only some scenarios (see bun benchmark --list).
bun benchmark --output ~/results                    # Save the report somewhere else.
bun benchmark --help                                # All the options.

Requirements:

  • Chrome and Firefox: they must be installed, and are driven using Puppeteer. Chrome runs headless (unless --headed is given), but a Firefox window opens, since headless Firefox doesn't draw using the GPU and caps its frame rate.
  • Safari (macOS only): it is driven using safaridriver, which must be enabled once, using safaridriver --enable and Safari's Develop › Allow Remote Automation menu item (the Develop menu can be shown in Safari's Advanced settings). A Safari window opens.
  • Browsers: by default, Chrome, Firefox, and (on macOS) Safari are used, skipping those that cannot be launched (e.g., if they are not installed).
  • Time: each scenario takes about 40 seconds, so all of them take about 10 minutes per browser (i.e. about half an hour for all three browsers). Don't use the computer in the meantime, since it would affect the results. On macOS, the benchmark keeps the display on while it runs (browsers stop drawing when the display is off), and refuses to start if the screen is locked.

A scenario is a kind of data (e.g., noisy sine waves or unsorted Lissajous curves, like in the demo app) with a number of plots, traces, and points (e.g., noisy-16-plots-3x100k is 16 plots of 3 noisy traces of 100,000 points). For each scenario, the benchmark zooms the plots in and out, pans them at a zoom of 1×, 10×, and 100× (the more zoomed in, the fewer the visible points), plots their data live (as if it was being generated), and resizes them, each for 5 seconds.

Reading the results:

  • Header: each table is preceded by the browser's version, the GPU, and the device pixel ratio.
  • Cells: the frame rate, and the average and 95th percentile of the redraw time (e.g., 800 FPS, 1.2/2.0 ms). The redraw time is the time it takes to redraw all the plots in a frame, including the browser rendering the frame. The lower, the better, and a 95th percentile much higher than the average means occasional stutters. At 60 Hz, a frame lasts 16.7 ms.
  • Frame rate: in Chrome and Firefox, it is not capped by the refresh rate of the display (unless --capped is given), so it tells how fast the plots can be redrawn. In Safari (or with --capped), it is capped by the refresh rate of the display, so compare redraw times instead.
  • First draw: the time from giving the data to the plots to them having drawn it, which includes creating the plots, processing the data, and building the levels of detail.

The results depend on the computer, the browser (and its version), and the display, so only compare results from the same computer. To measure the effect of a change, run the same scenarios before and after it.

Releasing

To publish a new version to npm, bump the version number (bun version:new), commit it, and push a tag named after it (i.e. vX.YYYYMMDD.Z for version X.YYYYMMDD.Z). Our CD workflow then tests, builds and publishes it. It fails if the tag doesn't match the version in package.json.

License

Apache License 2.0.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages