[英]Conditional formatting of plotly scatterplot markers
問題:
我有一個包含x
和y
值對的數據集,以及y
的lower_limit
和upper_limit
值。
我想在 plot.ly 散點圖中繪制x
與y
的關系,如果lower_limit
≤ y
≤ upper_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_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])
我建議創建一個新數組來存儲顏色值,請在下面找到使用np.where
和np.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])
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.