绘图散点图标记的条件格式

ebo*_*osi 2 python colors plotly plotly-python

问题:
我有一个包含xy值对、加号lower_limitupper_limit值的数据集y

我想在 plot.ly 散点图中绘制xvs.并将标记着色为绿色,如果? ,否则为红色ylower_limityupper_limit

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

示例:
考虑这个数据集:

   x   y  lower_limit  upper_limit
0  1  13           10           15
1  2  13           15           20
2  3  17           15           20
Run Code Online (Sandbox Code Playgroud)

第一个标记 ( x=1, y=13) 应该是绿色的,因为lower_limit? y? upper_limit(10 ? 13 ? 15),就像第三个一样。
但是第二个应该是红色的,因为y< lower_limit

然后我想生成这个图: 在此处输入图片说明


MWE:

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])
Run Code Online (Sandbox Code Playgroud)

Nar*_*ali 5

我建议创建一个新的数组来存储颜色值,请在下面找到使用的示例,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])
Run Code Online (Sandbox Code Playgroud)

参考:

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

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