Plotly散点图标记的条件格式化

5

问题:
我有一个数据集,其中包含xy值对,以及ylower_limitupper_limit值。

我想在plot.ly散点图中绘制x vs. y,并如果lower_limityupper_limit, 将标记颜色设为绿色,否则为红色

我知道可以使用2个跟踪轨迹,或者在DataFrame中添加color列。但是,我想即时生成这些颜色并仅使用一个跟踪轨迹。

示例:
考虑以下数据集:

   x   y  lower_limit  upper_limit
0  1  13           10           15
1  2  13           15           20
2  3  17           15           20

第一个标记(x=1,y=13)应该是绿色的,因为 lower_limityupper_limit(10 ≤ 13 ≤ 15),就像第三个一样。
然而,第二个标记应该是红色的,因为 y < lower_limit
然后我想生成这个图表: enter image description here
import pandas as pd
import plotly.graph_objs as go
import plotly.plotly as py
import plotly.offline as po

data = [
    [1, 13, 10, 15],
    [2, 13, 15, 20],
    [3, 17, 15, 20]
]

df = pd.DataFrame(
    data,
    columns=['x', 'y', 'lower_limit', 'upper_limit']
)

trace = go.Scatter(
    x=df['x'],
    y=df['y'],
    mode='markers',
    marker=dict(
        size=42,
        # I want the color to be green if 
        # lower_limit ≤ y ≤ upper_limit
        # else red
        color='green',
    )
)

po.plot([trace])
2个回答

7

我建议创建一个新的数组来存储颜色值,请参考下面的示例,其中使用了np.wherenp.logical_and来形成条件比较。

import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
from plotly import tools
import pandas as pd
import numpy
init_notebook_mode(connected=True)
data = [
    [1, 13, 10, 15],
    [2, 13, 15, 20],
    [3, 17, 15, 20]
]

df = pd.DataFrame(
    data,
    columns=['x', 'y', 'lower_limit', 'upper_limit']
)

#df['color'] = np.where(np.logical_and(df['lower_limit'] >= df['y'], df['y']  <= df['upper_limit']), 'green', 'red')

trace = go.Scatter(
    x=df['x'],
    y=df['y'],
    mode='markers',
    marker=dict(
        size=42,
        # I want the color to be green if lower_limit ≤ y ≤ upper_limit
        # else red
        color=np.where(np.logical_and(df['lower_limit'] <= df['y'], df['y']  <= df['upper_limit']), 'green', 'red'),
    )
)

iplot([trace])

参考文献:

  1. Pandas: np.where在数据帧上使用多个条件

  2. Pandas:用于在DataFrame中设置值的三元条件运算符


感谢您的回答。然而,正如问题所述,我希望尽可能地不向表中添加列。 - ebosi
1
如果这样做,两种颜色的图例(或n个条件)都不会显示,你知道怎么做吗? - Henry Navarro

1
import pandas as pd
import numpy as np


df = pd.DataFrame({'x': {0: 1, 1: 2, 2: 3}, 'y': {0: 13, 1: 13, 2: 17}, 'lower_limit': {0: 10, 1: 15, 2: 15}, 'upper_limit': {0: 15, 1: 20, 2: 20}})

如果你真的不想给df添加一列:

fig = px.scatter(df,
     x='x',
     y='y',
     color=np.where(df['y'].between(df['lower_limit'], df['upper_limit']), 'green', 'red'),
     color_discrete_sequence=pd.Series(np.where(df['y'].between(df['lower_limit'], df['upper_limit']), 'green', 'red')).drop_duplicates(),
     size=len(df)*[3])
fig.show()

输出:

图1

如果您不介意新建一列:

df['color'] = np.where(df['y'].between(df['lower_limit'], df['upper_limit']), 'green', 'red')

fig = px.scatter(df,
     x='x',
     y='y',
     color='color',
     color_discrete_sequence=df['color'].drop_duplicates(),
     size=len(df)*[3])

结果相同:

图2


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接