gpt4 book ai didi

python - 在 Plotly 气泡图中标记特定气泡

转载 作者:行者123 更新时间:2023-11-30 22:15:32 24 4
gpt4 key购买 nike

我无法弄清楚如何在plot.ly 气泡图中标记特定气泡。我希望某些“异常”气泡在气泡内写入文本,而不是通过悬停文本。

假设我有以下数据:

import plotly.plotly as py
import plotly.graph_objs as go

trace0 = go.Scatter(
x=[1, 2, 3, 4],
y=[10, 11, 12, 13],
mode='markers',
marker=dict(
size=[40, 60, 80, 100],
)
)

data = [trace0]
py.iplot(data, filename='bubblechart-size')

我只想在对应于 (1,10) 和 (4,13) 的气泡上添加文本标记。此外,是否可以控制文本标记的位置?

最佳答案

您可以通过annotations来实现这一点.

这允许您在图表上写入您想要的任何文本并将其引用到您的数据。您还可以使用位置 anchor 或通过在 x 和 y 数据之上应用附加计算来控制文本的显示位置。例如:

x_data = [1, 2, 3, 4]
y_data = [10, 11, 12, 13]
z_data = [40, 60, 80, 100]

annotations = [
dict(
x=x,
y=y,
text='' if 4 > x > 1 else z, # Some conditional to define outliers
showarrow=False,
xanchor='center', # Position of text relative to x axis (left/right/center)
yanchor='middle', # Position of text relative to y axis (top/bottom/middle)
) for x, y, z in zip(x_data, y_data, z_data)
]

trace0 = go.Scatter(
x=x_data,
y=y_data,
mode='markers',
marker=dict(
size=z_data,
)
)

data = [trace0]
layout = go.Layout(annotations=annotations)

py.iplot(go.Figure(data=data, layout=layout), filename='bubblechart-size')

编辑

如果使用袖扣,则上述内容可以稍微调整为:

bubbles_to_annotate = df[(df['avg_pos'] < 2) | (df['avg_pos'] > 3)]  # Some conditional to define outliers
annotations = [
dict(
x=row['avg_pos'],
y=row['avg_neg'],
text=row['subreddit'],
showarrow=False,
xanchor='center', # Position of text relative to x axis (left/right/center)
yanchor='middle', # Position of text relative to y axis (top/bottom/middle)
) for _, row in bubbles_to_annotate.iterrows()
]

df.iplot(kind='bubble', x='avg_pos', y='avg_neg', size='counts',
text='subreddit', xTitle='Average Negative Sentiment',
yTitle='Average Positive Sentiment', annotations=annotations,
filename='simple-bubble-chart')

您仍然需要定义注释,因为您需要条件参数。然后通过注释将其直接传递给袖扣。

关于python - 在 Plotly 气泡图中标记特定气泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50277856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com