Andrey Popov
Andrey Popov

Reputation: 28

Simple bar chart in Holoviews breaks when I create Dynamic Object out of it

This is my code, it works bar for last line (commented out)

#imports
import pandas as pd
import numpy as np
import holoviews as hv

# loading holoviews engine
hv.extension('matplotlib') #('bokeh')

# creating dummy data
samples = 1000
countries_sample = np.random.choice(['GBR', 'ITA'], samples)
hours_sample = np.random.choice(list(range(0,23)), samples)
count = np.random.randint(1, 5, size=samples)

df_test = pd.DataFrame({'location_country_iso3': countries_sample, 'hour': hours_sample, 'Count': count})
df_test = df_test.groupby(['location_country_iso3', 'hour']).size() 

# function to draw output
def draw_bars(country):
    return hv.Bars(df_test
                  ).sort().select(location_country_iso3 = country)

# dynamic map out of the function, to select single country
dmap_bars = hv.DynamicMap(draw_bars, kdims = ['country'])

# specific country selection
dmap_bars['GBR']

## options for country selection (this breaks):
# dmap_bars.redim.values(country = ['GBR', 'ITA'])


The above code creates bar chart as intended, for the selected country:

code output

However, when I introduce options for the Dynamic Map object:

# options for country selection (this breaks):
dmap_bars.redim.values(country = ['GBR', 'ITA'])

The code breaks. Dynamic Map does not receive the required selection, while error message is completely unrelated and unhelpful. Error message is also different running on 'Bokeh' / 'Matplotlib' engines, below is for when running on 'Matplotlib':

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/opt/anaconda3/lib/python3.9/site-packages/IPython/core/formatters.py in __call__(self, obj, include, exclude)
    968 
    969             if method is not None:
--> 970                 return method(include=include, exclude=exclude)
    971             return None
    972         else:

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/core/dimension.py in _repr_mimebundle_(self, include, exclude)
   1291         combined and returned.
   1292         """
-> 1293         return Store.render(self)
   1294 
   1295 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/core/options.py in render(cls, obj)
   1416         data, metadata = {}, {}
   1417         for hook in hooks:
-> 1418             ret = hook(obj)
   1419             if ret is None:
   1420                 continue

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py in pprint_display(obj)
    275     if not ip.display_formatter.formatters['text/plain'].pprint:
    276         return None
--> 277     return display(obj, raw_output=True)
    278 
    279 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py in display(obj, raw_output, **kwargs)
    251     elif isinstance(obj, (HoloMap, DynamicMap)):
    252         with option_state(obj):
--> 253             output = map_display(obj)
    254     elif isinstance(obj, Plot):
    255         output = render(obj)

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py in wrapped(element)
    139         try:
    140             max_frames = OutputSettings.options['max_frames']
--> 141             mimebundle = fn(element, max_frames=max_frames)
    142             if mimebundle is None:
    143                 return {}, {}

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py in map_display(vmap, max_frames)
    199         return None
    200 
--> 201     return render(vmap)
    202 
    203 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py in render(obj, **kwargs)
     66         renderer = renderer.instance(fig='png')
     67 
---> 68     return renderer.components(obj, **kwargs)
     69 
     70 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/renderer.py in components(self, obj, fmt, comm, **kwargs)
    396 
    397         if embed or config.comms == 'default':
--> 398             return self._render_panel(plot, embed, comm)
    399         return self._render_ipywidget(plot)
    400 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/renderer.py in _render_panel(self, plot, embed, comm)
    403         doc = Document()
    404         with config.set(embed=embed):
--> 405             model = plot.layout._render_model(doc, comm)
    406         if embed:
    407             return render_model(model, comm)

~/opt/anaconda3/lib/python3.9/site-packages/panel/viewable.py in _render_model(self, doc, comm)
    505         if comm is None:
    506             comm = state._comm_manager.get_server_comm()
--> 507         model = self.get_root(doc, comm)
    508 
    509         if config.embed:

~/opt/anaconda3/lib/python3.9/site-packages/panel/viewable.py in get_root(self, doc, comm, preprocess)
    556         """
    557         doc = init_doc(doc)
--> 558         root = self._get_model(doc, comm=comm)
    559         if preprocess:
    560             self._preprocess(root)

~/opt/anaconda3/lib/python3.9/site-packages/panel/layout/base.py in _get_model(self, doc, root, parent, comm)
    144         if root is None:
    145             root = model
--> 146         objects = self._get_objects(model, [], doc, root, comm)
    147         props = dict(self._init_params(), objects=objects)
    148         model.update(**self._process_param_change(props))

~/opt/anaconda3/lib/python3.9/site-packages/panel/layout/base.py in _get_objects(self, model, old_objects, doc, root, comm)
    129             else:
    130                 try:
--> 131                     child = pane._get_model(doc, root, model, comm)
    132                 except RerenderError:
    133                     return self._get_objects(model, current_objects[:i], doc, root, comm)

~/opt/anaconda3/lib/python3.9/site-packages/panel/pane/holoviews.py in _get_model(self, doc, root, parent, comm)
    270                   if p in Layoutable.param and p != 'name'}
    271         child_pane = self._get_pane(backend, state, **kwargs)
--> 272         self._update_plot(plot, child_pane)
    273         model = child_pane._get_model(doc, root, parent, comm)
    274         if ref in self._plots:

~/opt/anaconda3/lib/python3.9/site-packages/panel/pane/holoviews.py in _update_plot(self, plot, pane)
    215                     plot.update(key)
    216         else:
--> 217             plot.update(key)
    218             if hasattr(plot.renderer, 'get_plot_state'):
    219                 pane.object = plot.renderer.get_plot_state(plot)

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/mpl/plot.py in update(self, key)
    248         if len(self) == 1 and ((key == 0) or (key == self.keys[0])) and not self.drawn:
    249             return self.initialize_plot()
--> 250         return self.__getitem__(key)
    251 
    252 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/plot.py in __getitem__(self, frame)
    433         if not isinstance(frame, tuple):
    434             frame = self.keys[frame]
--> 435         self.update_frame(frame)
    436         return self.state
    437 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/mpl/plot.py in wrapper(self, *args, **kwargs)
     43     def wrapper(self, *args, **kwargs):
     44         with _rc_context(self.fig_rcparams):
---> 45             return f(self, *args, **kwargs)
     46     return wrapper
     47 

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/mpl/element.py in update_frame(self, key, ranges, element)
    487         label = element.label if self.show_legend else ''
    488         style = dict(label=labels.get(label, label), zorder=self.zorder, **self.style[self.cyclic_index])
--> 489         axis_kwargs = self.update_handles(key, axis, element, ranges, style)
    490         self._finalize_axis(key, element=element, ranges=ranges,
    491                             **(axis_kwargs if axis_kwargs else {}))

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/mpl/element.py in update_handles(self, key, axis, element, ranges, style)
    550         Update the elements of the plot.
    551         """
--> 552         self.teardown_handles()
    553         handles, axis_kwargs = self.render_artists(element, ranges, style, axis)
    554         self.handles.update(handles)

~/opt/anaconda3/lib/python3.9/site-packages/holoviews/plotting/mpl/element.py in teardown_handles(self)
    668         """
    669         if 'artist' in self.handles:
--> 670             self.handles['artist'].remove()
    671 
    672 

TypeError: list.remove() takes exactly one argument (0 given)

:DynamicMap   [country]
   :Bars   [location_country_iso3,hour]   (_)

Reinstalled fresh environment.

Tried recreating dummy data.

Tried moving various parts of the slicing (selection) process within draw_bars() function, using native hv.Dataset object to execute the slicing. Absolutely no difference.

Upvotes: 0

Views: 69

Answers (0)

Related Questions