Create colorbar from a source label (string) rather than integer? Python

When adding a colorbar to a scatterplot is it possible to assign strings for each color rather than numbers? I would like each data point to be referenced by the source it was collected from.

I have a dataset of many samples collecting from various site… rather than sorting each site and plotting individually as traces - I would just like a colorbar to reference each marker by color.

Or if I assign a number to each site is it possible to change the labels in the colorbar from that number to the site name?

Hi @spencerchad,

The marker.color property currently needs to be set to a number (though hopefully this will be more flexible in the future. see https://github.com/plotly/plotly.js/issues/1747). So the best approach for now is to customize the colorbar tick labels. Here’s a basic example

import plotly.graph_objs as go
import numpy as np

N = 100

color_names = ['A', 'B', 'C', 'D']
color_vals = list(range(len(color_names)))
num_colors = len(color_vals)
xs = np.random.rand(N)
ys = np.random.rand(N)
colors =  np.arange(N) % num_colors

fig = go.FigureWidget(data=[
    {'type': 'scatter',
     'mode': 'markers',
     'x': xs,
     'y': ys,
     'marker': {'color': colors,
                'size': 10,
                'colorbar': {
                    'tickvals': color_vals,
                    'ticktext': color_names
                }
               }}
])
fig

If you do a little extra work on the colorscale and colorbar, you can make something that looks more like a categorical legend:

import plotly.graph_objs as go
import numpy as np

N = 100

color_names = ['A', 'B', 'C', 'D']
color_vals = list(range(len(color_names)))
colors = ['red', 'green', 'blue', 'orange']

num_colors = len(color_vals)
xs = np.random.rand(N)
ys = np.random.rand(N)
colors =  np.arange(N) % num_colors

colorscale = [
    [0, 'red'],
    [0.25, 'red'],
    [0.25, 'green'],
    [0.5, 'green'],
    [0.5, 'blue'],
    [0.75, 'blue'],
    [0.75, 'orange'],
    [1, 'orange']]
cmin = -0.5
cmax = num_colors - 0.5

colorscale

fig = go.FigureWidget(data=[
    {'type': 'scatter',
     'mode': 'markers',
     'x': xs,
     'y': ys,
     'marker': {'color': colors,
                'size': 10,
                'colorbar': {
                    'tickvals': color_vals,
                    'ticktext': color_names,
                    'y': 1,
                    'len': 0.4,
                    'yanchor': 'top'
                },
                'colorscale': colorscale,
                'cmin': cmin,
                'cmax': cmax
               }}
])
fig

Hope that helps!
-Jon

1 Like

Thanks @jmmease. That is a helpful demonstration of a work around to use currently.

1 Like