Back to Lightweight Charts

Legends

website/tutorials/how_to/legends.mdx

5.2.02.8 KB
Original Source

import VersionWarningAdmonition from "@site/src/components/VersionWarningAdmonition";

{/* Show warning when not on the latest published version Tutorials section isn't versioned yet, hence the need for the warning message THESE TUTORIALS NEED TO BE UPDATED FOR VERSION 4 */}

<VersionWarningAdmonition notCurrent="This example is for the latest published version of Lightweight Charts." type="caution" displayVersionMessage />

Lightweight Charts™ doesn't include a built-in legend feature, however it is something which can be added to your chart by following the examples presented below.

How to

In order to add a legend to the chart we need to create and position an html into the desired position above the chart. We can then subscribe to the crosshairMove events (subscribeCrosshairMove) provided by the IChartApi instance, and manually update the content within our html legend element.

js
chart.subscribeCrosshairMove(param => {
    let priceFormatted = '';
    if (param.time) {
        const dataPoint = param.seriesData.get(areaSeries);
        const price = data.value !== undefined ? data.value : data.close;
        priceFormatted = price.toFixed(2);
    }
    // legend is a html element which has already been created
    legend.innerHTML = `${symbolName} <strong>${priceFormatted}</strong>`;
});

The process of creating the legend html element and positioning can be seen within the examples below. Essentially, we create a new div element within the container div (holding the chart) and then position and style it using css.

You can see full working examples below.

Resources

Below are a few external resources related to creating and styling html elements:

Examples

import UsageGuidePartial from "../_usage-guide-partial.mdx";

<UsageGuidePartial />

import CodeBlock from "@theme/CodeBlock";

Simple Legend Example

import codeLegend from "!!raw-loader!./legend.js";

<CodeBlock replaceThemeConstants chart className="language-js" hideableCode chartOnTop> {codeLegend} </CodeBlock>

3 Line Legend Example

import code3Line from "!!raw-loader!./legend-3line.js";

<CodeBlock replaceThemeConstants chart className="language-js" hideableCode chartOnTop> {code3Line} </CodeBlock>