[英]Coloring points in a plotly box plot by column variable
我希望根據數據框(已提交)中的列值更改框 plot 中點的顏色。
users = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
cost = [87.25, 84.69, 82.32, 87.25, 84.59, 82.32, 89.45, 86.37, 83.83]
committed = ['f', 'f', 't', 't', 'f', 'f', 'f', 't', 'f']
df = pd.DataFrame({'user': users, 'cost': cost, 'committed': committed})
為了得到下面的 plot,我輸入了這個:
fig = go.Figure(
data=[go.Box(
x=df['user'],
y=df['cost'],
boxpoints='all',
jitter=.3,
pointpos=-1.8,
)]
)
fig.show()
我找到了 r 的這篇文章,並希望在過去的 5 年里,有些事情發生了變化,使之成為可能: 通過組變量在 plotly 框 plot 中着色抖動
我試過這個,但 marker 或 marker_color 似乎沒有接受我的嘗試,我不確定如何設置其他值。
def set_color(point):
if point == 't':
return "red"
elif point == 'f':
return "blue"
fig = go.Figure(
data=[go.Box(
x=df['user'],
y=df['cost'],
boxpoints='all',
jitter=.3,
pointpos=-1.8,
marker=dict(color=list(map(set_color, df['committed'])))
)]
)
fig.show()
錯誤:
Invalid value of type 'builtins.list' received for the 'color' property of box.marker
我最終在這里找到了答案: Plotting data points over a box plot with specific colors & jitter in plotly
我的解決方案:
import plotly.express as px
import plotly.graph_objects as go
fig = px.strip(
df, x='user', y='cost', color='committed', stripmode="overlay"
)
for user in df['user'].unique():
fig.add_trace(go.Box(y=df.query(f'user == "{user}"')['cost'], name=user, marker_color="aquamarine"))
fig.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.