Reputation: 103
I have a pandas dataframe (df) with 4 columns, named 'name', 'nb', 'a' and 'b', that characterize a person, with his name, his id number ('nb') and some values ('a' and 'b') associated to it.
import pandas as pd
data = {
"name": ["Thomas", "John", "Anna", "Ben", "Arlette"],
'nb': [1,2,3,4,5],
"a": [0, 2, 13, 43, 90],
"b": [4, 24, 31, 2, 3],
}
df = pd.DataFrame(data)
I would like to create a scatter plot with the "a" and "b" values where the name and id would appear inside a tooltip. I think I can do that with the bqplot libary.
I wrote the following code :
from bqplot import pyplot as plt
from bqplot import Tooltip
from bqplot import Scatter
fig = plt.figure(title='My title')
def_tt = Tooltip(fields=['name','nb'], formats = ['','.2f'], labels = ['Name','Nb'],show_labels = True )
chart = plt.scatter(df["a"],df["b"], colors = ['red'], tooltip = def_tt, stroke = 'red', unhovered_style ={'opacity':0.5})
fig
But the tooltips are empty, although the labels appear. I think I am missing something in the def_tt line, the fields parameters are probably uncorrect.
Upvotes: 4
Views: 1646
Reputation: 4507
You can also create a new column in your dataframe, use it as a name and display the name in the tooltip:
fig = plt.figure()
def_tt = Tooltip(fields=['name'], show_labels=False)
df['labels'] = df.apply(lambda row: f'X: {row.x:%Y-%m-%d}, Y: {row.y:.2f}, Other Info: {row.custom_field}', axis=1)
scatt = plt.scatter(df.x, df.y, tooltip=def_tt,
# specify labels, but hide by default
names=df.labels, display_names=False)
fig
But it will not support rich formatting. Not even line breaks :(
Upvotes: 1
Reputation: 5565
With bqplot Tooltips, you can reference only the fields in the actual Mark. So something like this should work:
def_tt = Tooltip(fields=['index', 'x', 'y'], formats = ['','.2f'],)
If you want to pick up a different field from your dataframe, then you need to
1) create an output widget
2) define a function to run when you hover over a marker
3) set that output widget as the mark tooltip
4) Set that function to display your metadata in the output widget when you hover the mark.
from bqplot import pyplot as plt
from bqplot import Tooltip
from bqplot import Scatter
from ipywidgets import Output
fig = plt.figure(title='My title')
out = Output(). # 1
def def_tt(_, event): # 2
out.clear_output()
with out:
print(df.loc[event['data']['index'], 'name'])
chart = plt.scatter(
df["a"], df["b"], colors = ['red'],
tooltip = out, # 3
stroke = 'red', unhovered_style ={'opacity':0.5}
)
chart.on_hover(def_tt) # 4
fig
Upvotes: 3