Python绘制散点图颜色的实验研究

2024-09-24 02:25:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图复制Plotly R中的一个基本例子 https://plot.ly/r/line-and-scatter/#qualitative-colorscales 变成了多愁善感的Python。 但发现这是不可能的。在

同样的问题在R中也得到了解决: 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')
                    )

```

我得到的最接近的是使用colorbar,但这是次优的,因为我不知道如何选择颜色,这样它们就不会混合在一起,然后颜色图例使图形看起来像是有一些连续的数据,而不是这样。在


Tags: andhttpsgoplot颜色linelyplotly
1条回答
网友
1楼 · 发布于 2024-09-24 02:25:10

使用字典并相应地映射颜色:

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

相关问题 更多 >