3
votes

I'm trying to replicate one of the basic examples in Plotly R into Plotly Python, but finding it impossible.

The same problem is also solved in R here: Plotly assigning colors based on label

trace0 = go.Scatter( x = x1, y = y1, mode = 'markers',
                    name = ytitle +  ' X vs ' + Atitle, 
                    marker=dict(size=4, symbol='circle', 
                                color=colorsIdx, colorbar= go.ColorBar(title= 'colorbar'),
                            colorscale='Viridis')
                    )

The closest I've gotten is using a colorbar, but that is suboptimal since I can't figure out how to pick colors so that they don't blend together, and then the color legend makes the graph look like there's some continuous data going on which is not the case.

1

1 Answers

14
votes

Use a dictionary and map the colors accordingly:

import pandas as pd 
import plotly.plotly as py
import plotly.graph_objs as go

d  = {'x': [1, 2, 3], 'y': [3, 4, 5], 'z': ['A', 'B', 'A']}
df = pd.DataFrame(data=d)

colorsIdx = {'A': 'rgb(215,48,39)', 'B': 'rgb(215,148,39)'}
cols      = df['z'].map(colorsIdx)

# Create a trace
trace = go.Scatter(
    x = df.x,
    y = df.y,
    mode = 'markers',
    marker=dict(size=15, color=cols)
)

data = [trace]
py.iplot(data)

enter image description here