dataset: https://github.com/rashida048/Datasets/blob/master/StudentsPerformance.csv
I am trying to implement the hovertool function to display the value for the "Total" (sum of the 3 score columns) on each outlier. but when I hover over each value only ??? is displayed. I have also tried moving "source" inside the body of the function, as well as defining '@tot' in the hovertool as '@df.Total' and vice versa but still no success. where have I gone wrong? image attached.
source=ColumnDataSource(data=dict(df,tot=df.Total))
def box_plot(df, vals, label, ylabel=None,xlabel=None,title=None):
# Group Data frame
df_gb = df.groupby(label)
# Get the categories
cats = list(df_gb.groups.keys())
# Compute quartiles for each group
q1 = df_gb[vals].quantile(q=0.25)
q2 = df_gb[vals].quantile(q=0.5)
q3 = df_gb[vals].quantile(q=0.75)
# Compute interquartile region and upper and lower bounds for outliers
iqr = q3 - q1
upper_cutoff = q3 + 1.5*iqr
lower_cutoff = q1 - 1.5*iqr
# Find the outliers for each category
def outliers(group):
cat = group.name
outlier_inds = (group[vals] > upper_cutoff[cat]) \
| (group[vals] < lower_cutoff[cat])
return group[vals][outlier_inds]
# Apply outlier finder
out = df_gb.apply(outliers).dropna()
# Points of outliers for plotting
outx = []
outy = []
for cat in cats:
# only add outliers if they exist
if cat in out and not out[cat].empty:
for value in out[cat]:
outx.append(cat)
outy.append(value)
# If outliers, shrink whiskers to smallest and largest non-outlier
qmin = df_gb[vals].min()
qmax = df_gb[vals].max()
upper = [min([x,y]) for (x,y) in zip(qmax, upper_cutoff)]
lower = [max([x,y]) for (x,y) in zip(qmin, lower_cutoff)]
cats = [str(i) for i in cats]
# Build figure
p = figure(sizing_mode='stretch_width', x_range=cats,height=300,toolbar_location=None)
p.xgrid.grid_line_color = None
p.ygrid.grid_line_width = 2
p.yaxis.axis_label = ylabel
p.xaxis.axis_label = xlabel
p.title=title
p.y_range.start=0
p.title.align = 'center'
# stems
p.segment(cats, upper, cats, q3, line_width=2, line_color="black")
p.segment(cats, lower, cats, q1, line_width=2, line_color="black")
# boxes
p.rect(cats, (q3 + q1)/2, 0.5, q3 - q1, fill_color=['#a50f15', '#de2d26', '#fb6a4a', '#fcae91', '#fee5d9'],
alpha=0.7, line_width=2, line_color="black")
# median (almost-0 height rects simpler than segments)
p.rect(cats, q2, 0.5, 0.01, line_color="black", line_width=2)
# whiskers (almost-0 height rects simpler than segments)
p.rect(cats, lower, 0.2, 0.01, line_color="black")
p.rect(cats, upper, 0.2, 0.01, line_color="black")
# outliers
p.circle(outx, outy, size=6, color="black")
p.add_tools(HoverTool(tooltips=[('Total','@tot')]))
return p
p = box_plot(df, 'Total', 'race/ethnicity', ylabel='Total spread',xlabel='Race/Ethnicity',title='BoxPlot')
show(p)
the error i get after implementing your changes @mosc
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Input In [18], in <cell line: 86>()
82 p.add_tools(HoverTool(tooltips=[('Total','@tot')]))
84 return p
---> 86 p = box_plot(df, 'Total', 'race/ethnicity', ylabel='Total spread',xlabel='Race/Ethnicity',title='BoxPlot')
87 show(p)
Input In [18], in box_plot(df, vals, label, ylabel, xlabel, title)
77 p.rect(cats, upper, 0.2, 0.01, line_color="black")
79 # outliers
---> 80 p.circle(outx, outy, size=6, color="black", source=outliers_source)
82 p.add_tools(HoverTool(tooltips=[('Total','@tot')]))
84 return p
File ~\Anaconda3\lib\site-packages\bokeh\plotting\_decorators.py:86, in glyph_method.<locals>.decorator.<locals>.wrapped(self, *args, **kwargs)
84 if self.coordinates is not None:
85 kwargs.setdefault("coordinates", self.coordinates)
---> 86 return create_renderer(glyphclass, self.plot, **kwargs)
File ~\Anaconda3\lib\site-packages\bokeh\plotting\_renderer.py:96, in create_renderer(glyphclass, plot, **kwargs)
94 incompatible_literal_spec_values += _process_sequence_literals(glyphclass, glyph_visuals, source, is_user_source)
95 if incompatible_literal_spec_values:
---> 96 raise RuntimeError(_GLYPH_SOURCE_MSG % nice_join(incompatible_literal_spec_values, conjuction="and"))
98 # handle the nonselection glyph, we always set one
99 nonselection_visuals = pop_visuals(glyphclass, kwargs, prefix='nonselection_', defaults=glyph_visuals, override_defaults={'alpha':0.1})
RuntimeError:
Expected x and y to reference fields in the supplied data source.
When a 'source' argument is passed to a glyph method, values that are sequences
(like lists or arrays) must come from references to data columns in the source.
For instance, as an example:
source = ColumnDataSource(data=dict(x=a_list, y=an_array))
p.circle(x='x', y='y', source=source, ...) # pass column names and a source
Alternatively, *all* data sequences may be provided as literals as long as a
source is *not* provided:
p.circle(x=a_list, y=an_array, ...) # pass actual sequences and no source