user171780
user171780

Reputation: 3115

Show only a few markers in plotly express

I am doing a plot with Plotly's line. My lines are "high resolution" in the sense that they have many points. I want to add one category using the symbol parameter like in the example here. That example works fine when there are few points, but because it adds one marker per point when the line is too dense it fails

This is an example of one of my plots without the symbol argument

enter image description here

and this is how it looks after I use symbol:

enter image description here

Some of the symbols are crosses and some are dots, of course this cannot be seen because of the high density of points. One solution would be to drop a fraction of points prior to doing the plot, but that would reduce the resolution of my traces.

Is it possible to tell Plotly to show only a fraction of the markers?

Upvotes: 1

Views: 1297

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31226

  • Have create some lines with 10k observations
  • you can sample these lines and add additional traces that carry the markers. In this case have chosen every 1000
  • marker symbols - have used different ones selected from list of valid ones

updated based on comments Define how many markers you want rather than at fixed step size.

import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import random
from plotly.validators.scatter.marker import SymbolValidator

x = np.linspace(50, 100, random.randint(5*10**4, 3*10**5))
fig = px.line(
    x=x, y=[np.vectorize(lambda x: (x / f) ** f)(x) for f in np.linspace(2, 2.7, 6)]
)

# 21 markers, n+1 because of 0th
marker_step = len(fig.data[0].x) // 20

for t, s in zip(
    fig.data,
    [
        s
        for s in SymbolValidator().values[2::3]
        if len(s) < 3 or not (s[-3:] == "dot" or s[-3:] == "pen")
    ],
):
    fig.add_traces(
        go.Scattergl(
            x=t.x[::marker_step],
            y=t.y[::marker_step],
            mode="markers",
            marker_color=t.line.color,
            marker_symbol=s,
            marker_size=10,
            showlegend=False,
        )
    )

fig

enter image description here

Upvotes: 1

Related Questions