如何根据Plotly中数据框中的另一列为标记着色?

2024-04-25 04:01:28 发布

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

我有一个数据框,如下所示,有3列。我使用“束”作为x值,使用“统一大小”作为y值,以形成散点图。但是我想根据第三列类为各个点着色。类值2为绿色,4为蓝色的点

以数据帧中的第一个点和最后一个点为例。第一个点的x值为5,y值为1,颜色为绿色,而最后一个点的x值为4,y值为8,颜色为蓝色

我尝试使用如图所示的if语句,但出现语法错误。有什么办法吗

 fig = go.Figure()
 fig.update_layout(width = 400, height = 400, template = 'plotly_white',xaxis_title = 'clump', yaxis_title = 'Unif Size')
 fig.add_trace(go.Scatter(x = data.Clump,
                          y = data.UnifSize,
                          mode = 'markers',
                          if data.Class == 2:
                              marker = duct(
                              color = 'green'
                              ) 
                          if data.Class == 4:
                             marker = dict(
                             color = 'yellow'
                             )
                     )))

enter image description here


Tags: 数据godataiftitle颜色fig语句
1条回答
网友
1楼 · 发布于 2024-04-25 04:01:28

例如,您可以执行以下操作:

创建示例xy数据,使用包含颜色所依赖条件的数组:

import numpy as np
x = [x for x in range(100)]
y = [3*each*np.random.normal(loc=1.0, scale=0.1) for each in range(100)]
condition = [np.random.randint(0,2) for x in range(100)]

具有与条件数组中的x对应的索引的y点和y点为:

[eachx for indexx, eachx in enumerate(x) if condition[indexx]==0]
[eachy for indexy, eachy in enumerate(y) if condition[indexy]==0]

如果我们希望x和y数组中的元素在条件数组中具有与1对应的索引,我们只需将0更改为1

[eachx for indexx, eachx in enumerate(x) if condition[indexx]==1]
[eachy for indexy, eachy in enumerate(y) if condition[indexy]==1]

或者,您可以使用zip

[eachx for eachx, eachcondition in zip(x, condition) if eachcondition==0]

其他人也是如此

这是一个有条件的列表理解,这里有很好的解释:https://stackoverflow.com/a/4260304/8565438

然后用2go.Scatter调用绘制2对数组

整个事情:

import numpy as np
x = [x for x in range(100)]
y = [3*each*np.random.normal(loc=1.0, scale=0.1) for each in range(100)]
condition = [np.random.randint(0,2) for x in range(100)]

import plotly.graph_objects as go
fig = go.Figure()
fig.update_layout(width = 400, height = 400, template = 'plotly_white',xaxis_title = 'clump', yaxis_title = 'Unif Size')
fig.add_trace(go.Scatter(x = [eachx for indexx, eachx in enumerate(x) if condition[indexx]==0],
                        y = [eachy for indexy, eachy in enumerate(y) if condition[indexy]==0],
                        mode = 'markers',marker = dict(color = 'green')))
fig.add_trace(go.Scatter(x = [eachx for indexx, eachx in enumerate(x) if condition[indexx]==1],
                        y = [eachy for indexy, eachy in enumerate(y) if condition[indexy]==1],
                        mode = 'markers',marker = dict(color = 'yellow')))
fig.show()

这将为您提供:

enter image description here

我相信这就是我们想要的


要从DataFrame列转换为list,建议使用以下命令:get list from pandas dataframe column

相关问题 更多 >