Scatterplot with concentration hue

A simple scatterplot can be created as follows:

a, b = np.random.lognormal(size=(2,500))
fig = go.FigureWidget()
trace = fig.add_scatter(x=a, y=b, mode='markers', marker=dict(size=10), opacity=0.2)
fig


I would like there to be a darker hue for the regions where the concentration is higher.

I can achieve that if I plot each point separately:

X = zip(a, b)
fig = go.FigureWidget()
for el in X:
    fig.add_scatter(x=[el[0]],y=[el[1]], marker=dict(size=10, color=trace.marker.color), opacity=0.2)
fig.layout.update(showlegend=False)
fig


Plotting each point separately seems to be somewhat inefficient.

Question: How can I achieve the same result without having to plot each point separately.


UPDATE:

I’ve just upgraded to 4.0.0 and it seems that I can’t use trace.marker.color.
How can I get the color of trace now?

@ursus, You can get the same result by using the marker’s opacity attribute instead of the trace’s. fig.add_scatter(x=a, y=b, mode='markers', marker=dict(size=10, opacity=0.2)).

Also, starting in version 4 of plotly.py fig.add_scatter() returns the entire fig object and not the newly added trace as it did before. This makes it possible to easily chain method calls but it means that you will need to use something like fig.add_scatter(x=a, y=b, mode='markers', marker=dict(size=10, opacity=0.2)).data[-1] if you want to get just the newly added trace.

Thank you, @michaelbabyn!

But, I still cannot get the marker color. Is that something that can be done in version 4?

@ursus, That works for me with Plotly.py 4.0 in jupyter notebook and jupyterlab but I can’t get it to work in jupyterlab. Where are you running your code and which versions of jupyter/notebook/ipywidgets are you using?

trace.data[-1].marker.color seems to work in jupyter notebook. I might have tried something different.

My version of notebook is 6.0.0.

My version of JupyterLab is 1.0.2 and unfortunately I cannot use it now. There appears to be an issue with it.

@ursus, did you ever get jupyterlab to load properly? I ran into a similar issue recently and I noticed the below error in my browser console regarding duplicate plugins being registered.

I was able to fix it by getting rid of the offending plugins from ~/.conda/envs/plotly-env/share/jupyter/lab/extensions/ and then reinstalling them.

Yes:

The question now is: why does that happen?

1 Like