0

I am struggling with something that is probably quite simple.
consider this: I have unit ids with data for each unit id.
I want to construct a bar graph and to be able to select whatever unit id I want.
To do this I chose plotly px. I am constructing the bars according to some range split method (using pd.cut)
The result I have is very close to what I want.
when I’m hovering on the different units on the graph I see the unit id, range, and exact value but the text is also plotted on the graph and makes the plot very messy.
I tried to use different px.bar attributed to replacing %{text}% but without success.

Small code that reproduces the plot I have

import dash_core_components as dcc
import numpy as np
import pandas as pd
import dash
import dash_html_components as html
import plotly.express as px

data = np.random.rand(300)
unit_id = np.random.choice(range(1000), 300, replace=False)
data_tuple = sorted([(str(uid), data) for uid, data in zip(unit_id, data)], key=lambda x: x[1])

y_data = [y[1] for y in data_tuple]
x_data = [i for i in range(1, len(y_data) + 1)]
range_bins = pd.cut(np.array(np.array(y_data).astype(float)), 10)
data_range_lbl = [str(v) for v in range_bins]

sorted_unit_id = [x[0] for x in data_tuple]
unit_id_text = [sorted_unit_id[i] + '<br><b>Value</b>: ' + str(y_data[i]) for i in range(0, len(sorted_unit_id))]
fig = px.bar(x=data_range_lbl, y=[1 for i in range(0, len(data_range_lbl))], text=unit_id_text)

fig.update_layout(dragmode='select')
fig.update_traces(hovertemplate=
                  '<b>Die Id</b>: %{text}' +
                  '<br><b>Range</b>: %{x}<br>')
app = dash.Dash(__name__)
app.layout = html.Div([
    html.Div(id='container-button-timestamp'),
    dcc.Graph(
        id='sample-graph', figure=fig
    ),
])

if __name__ == '__main__':
    app.run_server(debug=True, port=8050)

how it looks: enter image description here

1 Answer 1

2

using hovertext did the trick.

removed text from px.bar attributes:
fig = px.bar(x=data_range_lbl, y=[1 for i in range(0, len(data_range_lbl))])

and changed fig.update_traces:

fig.update_traces(
    hovertext=unit_id_text,
    hovertemplate=
    '<b>Die Id</b>: %{hovertext}' +
    '<br><b>Range</b>: %{x}<br>')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.