繁体   English   中英

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

[英]How to color markers based on another column in the dataframe in Plotly?

我有一个 dataframe 如下所示,有 3 列。 我使用 clump 作为我的 x 值和 Unif 大小作为我的 y 值来形成散点图。 但我想根据第三列 class 为各个点着色。 class 值 2 为绿色和 4 为蓝色的点。

所以以dataframe中的第一个和最后一个点为例。 第一个点的 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'
                             )
                     )))

在此处输入图像描述

例如,您可以这样做:

创建示例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)]

在条件数组中具有对应于0的索引的xy点是:

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

如果我们想要 x 和 y arrays 中的元素在条件数组中具有对应于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

然后 plot 2 对 arrays 与 2 go.Scatter调用。

整件事在一起:

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()

这会给你:

在此处输入图像描述

我相信这就是我们想要的。


要从DataFrame列转换为list ,建议这样做: 从 pandas dataframe 列获取列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM