Dan*_*les 5 python hover plotly
我知道跟踪(标记/线)有 hovertemplate/hover_text/ 选项,但我找不到形状这样的东西。有没有办法在形状上移动时弹出悬停文本?也许是一种解决方法?
例子:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1.5, 3],
y=[2.5, 2.5],
text=["Rectangle reference to the plot",
"Rectangle reference to the axes"],
mode="markers",
))
fig.add_shape(
# Rectangle reference to the plot
type="rect",
xref="paper",
yref="paper",
x0=0.25,
y0=0,
x1=0.5,
y1=0.5,
line=dict(
color="LightSeaGreen",
width=3,
),
fillcolor="PaleTurquoise",
)
Run Code Online (Sandbox Code Playgroud)
当我将鼠标悬停在这两点上时,我会得到一个包含信息的悬停模板。我怎样才能得到形状相似的东西?
似乎无法直接将hoverinfo添加到形状中。但是,通过形状和痕迹的正确组合,您可以获得非常接近所需效果的东西。下图是通过在列表中指定两个矩形来绘制的,如下所示:
shapes = [[2,6,2,6],
[4,7,4,7]]
Run Code Online (Sandbox Code Playgroud)
代码片段的其余部分在形状数量、分配给它们的颜色以及相应的迹线方面设置得灵活,以在形状的右下角制作那个小点。
阴谋:
如果这是您可以使用的东西,我们可以讨论编辑悬停信息中显示的内容的方法。
完整代码:
# Imports
import pandas as pd
#import matplotlib.pyplot as plt
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
# shape definitions
shapes = [[2,6,2,6],
[4,7,4,7]]
# color management
# define colors as a list
colors = px.colors.qualitative.Plotly
# convert plotly hex colors to rgba to enable transparency adjustments
def hex_rgba(hex, transparency):
col_hex = hex.lstrip('#')
col_rgb = list(int(col_hex[i:i+2], 16) for i in (0, 2, 4))
col_rgb.extend([transparency])
areacol = tuple(col_rgb)
return areacol
rgba = [hex_rgba(c, transparency=0.4) for c in colors]
colCycle = ['rgba'+str(elem) for elem in rgba]
# plotly setup
fig = go.Figure()
# shapes
for i, s in enumerate(shapes):
fig.add_shape(dict(type="rect",
x0=s[0],
y0=s[2],
x1=s[1],
y1=s[3],
layer='above',
fillcolor=colCycle[i],
line=dict(
color=colors[i],
width=3)))
# traces as dots in the lower right corner for each shape
for i, s in enumerate(shapes):
fig.add_trace(go.Scatter(x=[s[1]], y=[s[2]], name = "Hoverinfo " +str(i + 1),
showlegend=False,
mode='markers', marker=dict(color = colors[i], size=12)))
# edit layout
fig.update_layout(yaxis=dict(range=[0,8], showgrid=True),
xaxis=dict(range=[0,8], showgrid=True))
fig.show()
Run Code Online (Sandbox Code Playgroud)
我想到了一个令我满意的解决方案。简单地画一个形状。您将无法看到悬停文本。但是,如果您在形状顶部添加填充迹线,然后将迹线设置为 opacity=0,则在形状上移动时,您将看到迹线中弹出的悬停文本。再次感谢您的回复!
import plotly.graph_objects as go
# Draw shape (you won't be able to add a hover text for it)
fig = go.Figure()
fig.add_shape(
type="rect",
x0=0, y0=0,
x1=4, y1=3,
fillcolor='LightSkyBlue',
line_color='Blue',
name='Shape 1'
)
# Adding a trace with a fill, setting opacity to 0
fig.add_trace(
go.Scatter(
x=[0,0,4,4,0],
y=[0,3,3,0,0],
fill="toself",
mode='lines',
name='',
text='Custom text on top of shape',
opacity=0
)
)
fig.show()
Run Code Online (Sandbox Code Playgroud)