Search code examples
javascripthtmlplotlyplotly.js

How to have custom marker symbol('[' and ']') in Plotly.js


I'm working on a project that requires graphs. I'm using Plotly with JS.

I want custom symbols '[' or ']' as markers on the graph.
Although i prefer without usage of svg, I'm open to change.
How?

I tried:
HTML Code:

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Graphs</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
    <div id="graph-1"></div>
    <script src="index.js"></script>
</body>
</html>

JS Code:

index.js

graph_1_data = [{
    x: [1, 2, 3],
    y: [1, 2, 3],
    mode: 'lines+markers',
    line: {
        shape: 'linear',
        color: 'blue'
    },
    marker: { 
        symbol: "[", #Here even though I give '[' it's showing circle[it's default probably] on the plotted graph
        size: 15
    }
}]
graph_1_layout = {
    title: "Graph-1"
}
Plotly.newPlot('graph-1',graph_1_data, graph_1_layout); 

Please help me get Custom Markers('[' and ']' to be specific) in Plotly JS


Solution

  • Disclaimer - I am not a Plotly.js user. The suggested solution was made using an example given on the Plotly forums.

    You would need to replace lines+markers with lines+text, and then use the text property of the Plotly graph object to specify individual markers for each of the coordinates.

    For example:

    var graph_1_data = [{
        x: [1, 2, 3],
        y: [1, 2, 3],
        mode: 'lines+text',
        text: ['[','[','['],
        line: {
            shape: 'linear',
            color: 'blue'
        },
        textfont: {
          size: 25,
          color: 'blue'
        }
    }]
    graph_1_layout = {
        title: "Graph-1"
    }
    Plotly.newPlot('graph-1',graph_1_data, graph_1_layout); 
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <div id="graph-1"></div>

    Or, to avoid manually populating your text array with [:

    const xCoords = [1,2,3];
    const yCoords = [1,2,3];
    const markers = new Array(xCoords.length).fill('[');
    
    var graph_1_data = [{
        x: xCoords,
        y: yCoords,
        mode: 'lines+text',
        text: markers,
    // ... the rest of the code
    }]