Python - plotly assigning scatterplot colors by label

谁说胖子不能爱 提交于 2019-12-22 22:48:31

问题


I'm trying to replicate one of the basic examples in Plotly R https://plot.ly/r/line-and-scatter/#qualitative-colorscales 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:


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)



来源:https://stackoverflow.com/questions/49885837/python-plotly-assigning-scatterplot-colors-by-label

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!