簡體   English   中英

散點圖標記的條件格式

[英]Conditional formatting of plotly scatterplot markers

問題:
我有一個包含xy值對的數據集,以及ylower_limitupper_limit值。

我想在 plot.ly 散點圖中繪制xy的關系,如果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

然后我想生成這個圖表: 在此處輸入圖像描述


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

我建議創建一個新數組來存儲顏色值,請在下面找到使用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 中設置值的三元條件運算符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM