绘制破折号:如何将工具提示与顶部对齐,而不是右上

发布于 2025-02-09 13:27:13 字数 1483 浏览 2 评论 0原文

我希望工具提示(下图的突出显示部分)出现在垂直条的顶部,而当前在右侧。

甚至探索了绘图条形图的文档并看到了一些教程,但我无法找出解决此问题的解决方案。

数据帧和条形图代码:

df = pd.DataFrame({
    "Day": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
    "Amount": [4, 1, 2, 2, 4, 5,8],
})

fig = px.bar(df, x="Day", y="Amount",orientation="v",opacity=0.9,barmode='relative',color_discrete_sequence=["purple"],text='Day',template='none')
fig.update_traces(texttemplate = '%{text:.2s}',textposition = 'outside',width = [.3,.3,.3,.3,.3,.3,.3])

仪表板代码:

html.Div(className="bar-chart",children=[
                    html.H1('Weekly Statistics'),
                    dcc.Dropdown( 
    ['Last Week', 'Last Month', 'Last Year'],
    'Montreal',
    clearable=False,style={'outline':'none','text-decoration':'none','width':'32vw','margin-top':'10px','margin-right':'20px','color':'#28285F','text-align':'right'}
),

dcc.Graph(
    style = {
        'display':'flex',
        'flex-direction':'column',
        'align-items':'flex-start',
        'position':'absolute',
        'width':'40vw',
        'height':'20vw',
        'margin-left':'5vw',
        'margin-top':'6vw',
        'background':'rgba(85, 190, 155, 0.1)'
    },
        id='example-graph',
        figure=fig
    ),
                ]),

I would like the tooltip (highlighted part of the image below) to appear on the top of the vertical bar, while it is currently on the right.

enter image description here

Even explored documentation of plotly bar charts and saw some tutorials, but I am not able to figure out the solution for this problem.

Data frames and bar chart code:

df = pd.DataFrame({
    "Day": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
    "Amount": [4, 1, 2, 2, 4, 5,8],
})

fig = px.bar(df, x="Day", y="Amount",orientation="v",opacity=0.9,barmode='relative',color_discrete_sequence=["purple"],text='Day',template='none')
fig.update_traces(texttemplate = '%{text:.2s}',textposition = 'outside',width = [.3,.3,.3,.3,.3,.3,.3])

Dash code:

html.Div(className="bar-chart",children=[
                    html.H1('Weekly Statistics'),
                    dcc.Dropdown( 
    ['Last Week', 'Last Month', 'Last Year'],
    'Montreal',
    clearable=False,style={'outline':'none','text-decoration':'none','width':'32vw','margin-top':'10px','margin-right':'20px','color':'#28285F','text-align':'right'}
),

dcc.Graph(
    style = {
        'display':'flex',
        'flex-direction':'column',
        'align-items':'flex-start',
        'position':'absolute',
        'width':'40vw',
        'height':'20vw',
        'margin-left':'5vw',
        'margin-top':'6vw',
        'background':'rgba(85, 190, 155, 0.1)'
    },
        id='example-graph',
        figure=fig
    ),
                ]),

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

献世佛 2025-02-16 13:27:13

您可以选择将工具提示放在顶部,右(默认),底部或左上角,然后我应用了官方工具提示示例到您的代码。我设置了创建的初始图,以没有悬停关联。我从用户收到悬停点信息,并将其显示在框中。默认情况下,在显示加载显示后,将显示悬停信息,因为它是用户的回调。我是Dash的新手,并从正式参考资料中获取了我的大部分信息。

from dash import Dash, dcc, html, Input, Output, no_update
#from jupyter_dash import JupyterDash
import plotly.express as px
import pandas as pd
import time

df = pd.DataFrame({
    "Day": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
    "Amount": [4, 1, 2, 2, 4, 5,8],
})

fig = px.bar(df, x="Day", y="Amount",
             orientation="v",
             opacity=0.9,
             barmode='relative',
             color_discrete_sequence=["purple"],
             text='Amount',
             hover_data=None,
             template='none')

fig.update_traces(texttemplate='%{text:.2s}',
                  hovertemplate=None,
                  hoverinfo='none',
                  textposition='outside',
                  width = [.3,.3,.3,.3,.3,.3,.3]
                 )
fig.update_layout(yaxis=dict(range=[0,10]))
#fig.show()

app = Dash(__name__)
#app = JupyterDash(__name__)

app.layout = html.Div(
    className="container",
    children=[
        dcc.Graph(
            id="graph-4",
            figure=fig,
            clear_on_unhover=True),
        dcc.Tooltip(
            id="graph-tooltip-4",
            loading_text="LOADING",
            direction="top"),
    ],
)

# This callback is executed very quickly
app.clientside_callback(
    """
    function show_tooltip(hoverData) {
        if(!hoverData) {
            return [false, dash_clientside.no_update];
        }
        var pt = hoverData.points[0];
        return [true, pt.bbox];
    }
    """,
    Output("graph-tooltip-4", "show"),
    Output("graph-tooltip-4", "bbox"),
    Input("graph-4", "hoverData"),
)

# This callback is executed after 1s to simulate a long-running process
@app.callback(
    Output("graph-tooltip-4", "children"),
    Input("graph-4", "hoverData"),
)
def update_tooltip_content(hoverData):
    if hoverData is None:
        return no_update

    time.sleep(1)

    hover_data = hoverData["points"][0]

    # Display the x0 and y0 coordinate
    #bbox = hoverData["points"][0]["bbox"]
    y = hover_data['y']
    x = hover_data['x']
    # print('x:', x, 'y:',y)
    return [
        html.P(f"Day={x}, Amount={y}"),
    ]

if __name__ == "__main__":
    app.run_server(debug=True)#, mode='inline'

You can choose to position the tooltip at the top, right (default), bottom, or left, and I have applied the official tooltip example to your code. I have set the initial graph I create to have no hover association. I receive hover point information from the user and display it in a box. By default, the hover information is displayed after the loading display is displayed since it is a callback from the user. I am a novice in Dash and have taken most of my information from the official reference.

from dash import Dash, dcc, html, Input, Output, no_update
#from jupyter_dash import JupyterDash
import plotly.express as px
import pandas as pd
import time

df = pd.DataFrame({
    "Day": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
    "Amount": [4, 1, 2, 2, 4, 5,8],
})

fig = px.bar(df, x="Day", y="Amount",
             orientation="v",
             opacity=0.9,
             barmode='relative',
             color_discrete_sequence=["purple"],
             text='Amount',
             hover_data=None,
             template='none')

fig.update_traces(texttemplate='%{text:.2s}',
                  hovertemplate=None,
                  hoverinfo='none',
                  textposition='outside',
                  width = [.3,.3,.3,.3,.3,.3,.3]
                 )
fig.update_layout(yaxis=dict(range=[0,10]))
#fig.show()

app = Dash(__name__)
#app = JupyterDash(__name__)

app.layout = html.Div(
    className="container",
    children=[
        dcc.Graph(
            id="graph-4",
            figure=fig,
            clear_on_unhover=True),
        dcc.Tooltip(
            id="graph-tooltip-4",
            loading_text="LOADING",
            direction="top"),
    ],
)

# This callback is executed very quickly
app.clientside_callback(
    """
    function show_tooltip(hoverData) {
        if(!hoverData) {
            return [false, dash_clientside.no_update];
        }
        var pt = hoverData.points[0];
        return [true, pt.bbox];
    }
    """,
    Output("graph-tooltip-4", "show"),
    Output("graph-tooltip-4", "bbox"),
    Input("graph-4", "hoverData"),
)

# This callback is executed after 1s to simulate a long-running process
@app.callback(
    Output("graph-tooltip-4", "children"),
    Input("graph-4", "hoverData"),
)
def update_tooltip_content(hoverData):
    if hoverData is None:
        return no_update

    time.sleep(1)

    hover_data = hoverData["points"][0]

    # Display the x0 and y0 coordinate
    #bbox = hoverData["points"][0]["bbox"]
    y = hover_data['y']
    x = hover_data['x']
    # print('x:', x, 'y:',y)
    return [
        html.P(f"Day={x}, Amount={y}"),
    ]

if __name__ == "__main__":
    app.run_server(debug=True)#, mode='inline'

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文