def hist(self, x, y, data=None): plot_opts = dict(self._plot_opts) invert = self.kwds.get('orientation', False) == 'horizontal' opts = dict(plot=dict(plot_opts, labelled=['x'], invert_axes=invert), style=self._style_opts, norm=self._norm_opts) hist_opts = { 'num_bins': self.kwds.get('bins', 10), 'bin_range': self.kwds.get('bin_range', None), 'normed': self.kwds.get('normed', False) } data = self.data if data is None else data ds = Dataset(data) if y and self.by: return histogram(ds.to(Dataset, [], y, self.by), **hist_opts).\ overlay().opts({'Histogram': opts}) elif y: return histogram(ds, dimension=y, **hist_opts).\ opts({'Histogram': opts}) hists = {} columns = self.columns or data.columns for col in columns: hist = histogram(ds, dimension=col, **hist_opts) ranges = {hist.vdims[0].name: self._dim_ranges['y']} hists[col] = (hist.redim.range(**ranges).relabel( **self._relabel).opts(**opts)) return NdOverlay(hists)
def plot_phase_diagrams(filenames,fileout): for i in range(len(filenames)): print 'i: ',i ds = yt.load(filenames[i]) center_guess = initial_center_guess(ds,track_name) halo_center = get_halo_center(ds,center_guess) rb = sym_refine_box(ds,halo_center) args = filenames[i].split('/') sim_label = args[-3] dens = np.log10(rb['H_nuclei_density']) temp = np.log10(rb['Temperature']) df = pd.DataFrame({'temp':temp, 'dens':dens}) phase_scatter = hv.Scatter(df,kdims=['dens'],vdims=['temp'],label=sim_label) #phase_data = np.zeros((len(rb['H_nuclei_density']),2)) #phase_data[:,0] = np.log10(rb['H_nuclei_density']) #phase_data[:,1] = np.log10(rb['Temperature']) #points = hv.Points(phase_data,kdims=['nH','temp'],label=sim_label) hv.opts({'Histogram': {'style': {'alpha':0.3, 'fill_color':'k'}}}) xhist = (histogram(phase_scatter, bin_range=(-7.5, 1), dimension='dens',normed=True)) #,alpha=0.3, fill_color='k')) yhist = (histogram(phase_scatter, bin_range=(3, 8.5), dimension='temp',normed=True)) #,alpha=0.3, fill_color='k')) if i == 0: phase_plot = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125)) else: plot2 = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125)) phase_plot = phase_plot + plot2 renderer = hv.renderer('bokeh').instance(fig='html') renderer.save(phase_plot, fileout) return
def _h(Counts, index, fine_index, **kwargs): #print index, kwargs from holoviews.operation import histogram m = { Counts: "Value", "{}_frequency": "frequency", } if len(index) > 0: d = self._data.embedding.iloc[index] if len(fine_index) > 0: d = d.iloc[fine_index] #print "Trying", Counts label = "{} {} points".format(Counts, len(d)) r = histogram( hv.Points(d), #self.selected_table, dimension=Counts, dynamic=False).redim(**m) else: label = "{} {} points".format(Counts, len(self._data.embedding)) #print "Alt", Counts r = histogram(self._points[Counts], dimension="Value", dynamic=False).redim(Value_frequency="frequency") #print(r) return r.relabel(label)
def generateCombined(self, decimated, SSC, FSC, cachebust, counter_max=20): renderer = hv.renderer('bokeh') body = None points = None point_collect = [] for key in decimated.keys(): print(key) point = hv.Scatter(decimated[key], SSC, FSC, label=key) point_collect.append(point) if points is None: points = point else: points *= point if body is None: body = points.opts(title='Default {0}: SSC vs FSC'.format("Combined"), height=450, width=450) else: body += points.opts(title='Default {0}: SSC vs FSC'.format("Combined")) for dim in (SSC, FSC): hists = None for point in point_collect: hist = histogram(point, dimension=dim) if hists is None: hists = hist else: hists *= hist body += hists potentialCols = [c for c in decimated[list(decimated.keys())[0]].columns if c != SSC and c != FSC] for i in range(len(potentialCols)): for j in range(i+1, len(potentialCols)): points = None point_collect = [] for key in decimated.keys(): point = hv.Scatter(decimated[key], potentialCols[i], potentialCols[j], label=key) point_collect.append(point) if points is None: points = point else: points *= point body += points.opts(title='Combined: {0} vs {1}'.format(potentialCols[i], potentialCols[j]), height=450, width=450) for dim in (potentialCols[i], potentialCols[j]): hists = None for point in point_collect: hist = histogram(point, dimension=dim) if hists is None: hists = hist else: hists *= hist body += hists body = body.opts( opts.Scatter(alpha=0.9), opts.Histogram(alpha=0.9, height=450), opts.Layout(shared_axes=True, shared_datasource=True)).cols(3) renderer.save(body, os.path.join(self.directory, cachebust+"combined_gating"))
def hist(self, x, y, data=None): data, x, y = self._process_args(data, x, y) labelled = ['y'] if self.invert else ['x'] plot_opts = dict(self._plot_opts, labelled=labelled) opts = dict(plot=plot_opts, style=self._style_opts, norm=self._norm_opts) hist_opts = { 'bin_range': self.kwds.get('bin_range', None), 'normed': self.kwds.get('normed', False), 'cumulative': self.kwds.get('cumulative', False) } if 'bins' in self.kwds: bins = self.kwds['bins'] if isinstance(bins, int): hist_opts['num_bins'] = bins else: hist_opts['bins'] = bins if not isinstance(y, (list, tuple)): if self.stacked and not self.subplots and not 'bin_range' in self.kwds: ys = data[y] hist_opts['bin_range'] = (ys.min(), ys.max()) ds = Dataset(data, self.by, y) hist = hists = histogram(ds.to(Dataset, [], y, self.by), **hist_opts) if self.by: hist = hists.last hists = hists.layout() if self.subplots else hists.overlay() ranges = { hist.kdims[0].name: self._dim_ranges['x'], hist.vdims[0].name: self._dim_ranges['y'] } return hists.opts({ 'Histogram': opts }).redim(**self._redim).redim.range(**ranges) ds = Dataset(data) hists = [] for col in y: hist = histogram(ds, dimension=col, **hist_opts) ranges = { hist.kdims[0].name: self._dim_ranges['x'], hist.vdims[0].name: self._dim_ranges['y'] } hists.append((col, hist.redim.range(**ranges).relabel( **self._relabel).opts(**opts))) return self._by_type(hists, sort=False).redim(**self._redim)
def test_histogram_datetime64_plot(self): dates = np.array([dt.datetime(2017, 1, i) for i in range(1, 5)]) hist = histogram(Dataset(dates, 'Date'), num_bins=4) plot = bokeh_renderer.get_plot(hist) source = plot.handles['source'] data = { 'top': np.array([ 3.85802469e-18, 3.85802469e-18, 3.85802469e-18, 3.85802469e-18 ]), 'left': np.array([ '2017-01-01T00:00:00.000000', '2017-01-01T17:59:59.999999', '2017-01-02T12:00:00.000000', '2017-01-03T06:00:00.000000' ], dtype='datetime64[us]'), 'right': np.array([ '2017-01-01T17:59:59.999999', '2017-01-02T12:00:00.000000', '2017-01-03T06:00:00.000000', '2017-01-04T00:00:00.000000' ], dtype='datetime64[us]') } for k, v in data.items(): self.assertEqual(source.data[k], v) xaxis = plot.handles['xaxis'] range_x = plot.handles['x_range'] self.assertIsInstance(xaxis, DatetimeAxis) self.assertEqual(range_x.start, np.datetime64('2017-01-01T00:00:00.000000', 'us')) self.assertEqual(range_x.end, np.datetime64('2017-01-04T00:00:00.000000', 'us'))
def update_hist(self): hv.extension("matplotlib") dcrop = (self.da_masked * self.da_zone.sel(id=self.id_i)).isel(step=self.step) dcrop.name = self.da.name var_name = self.da.name if self.levels: hv_img = hv.Image(hv.Dataset(dcrop), kdims=["longitude", "latitude" ]).opts(colorbar=True, color_levels=self.levels, cmap=self.colors) html_map = hv.renderer("matplotlib").html(hv_img) else: hv_img = hv.Image(hv.Dataset(dcrop), kdims=["longitude", "latitude"]).opts(colorbar=True, color_levels=30) html_map = hv.renderer("matplotlib").html(hv_img) # Si besoin de specifier le range : hv_img.redim.__getattribute__("range")(**{var_name:(self.vmin,self.vmax)})) dstack = dcrop.stack(z=("latitude", "longitude")).reset_index("z") dstack["z"] = range(len(dstack.z)) dstack.name = self.da.name hv_dst = hv.Dataset(dstack) k = histogram(hv_dst, dynamic=True, name="Test") html = ''' <h4> Histogramme sur {} </h4> de {}'''.format( self.hist_name, self.variable) self.html2.value = html + hv.renderer("matplotlib").html(k) + html_map
def test_dynamic_operation_init_renamed_stream_params(self): img = Image(sine_array(0, 5)) stream = RangeX(rename={'x_range': 'bin_range'}) dmap_with_fn = histogram(img, bin_range=(0, 1), streams=[stream], dynamic=True) self.assertEqual(stream.x_range, (0, 1))
def test_dynamic_operation_init_stream_params(self): img = Image(sine_array(0, 5)) stream = Stream.define('TestStream', bin_range=None)() dmap_with_fn = histogram(img, bin_range=(0, 1), streams=[stream], dynamic=True) self.assertEqual(stream.bin_range, (0, 1))
def test_histogram_datetime64_plot(self): dates = np.array([dt.datetime(2017, 1, i) for i in range(1, 5)]) hist = histogram(Dataset(dates, 'Date'), num_bins=4) plot = mpl_renderer.get_plot(hist) artist = plot.handles['artist'] ax = plot.handles['axis'] self.assertEqual(ax.get_xlim(), (736330.0, 736333.0)) bounds = [736330.0, 736330.75, 736331.5, 736332.25] self.assertEqual([p.get_x() for p in artist.patches], bounds)
def modify_doc(doc): points = hv.Points(np.random.randn(10000, 2)) points2 = hv.Points(np.random.randn(100, 2) * 2 + 1) xhist, yhist = (histogram(points2, bin_range=(-5, 5), dimension=dim) * histogram(points, bin_range=(-5, 5), dimension=dim) for dim in 'xy') composition = (points2 * points) << yhist.opts(width=125) << xhist.opts(height=125) composition.opts(opts.Histogram(alpha=0.3)) final = composition plot = renderer.get_plot(final) layout = row(plot.state) # renderer.server_doc(layout) doc.add_root(layout)
def test_histogram_datetime64_plot(self): dates = np.array([dt.datetime(2017, 1, i) for i in range(1, 5)]) hist = histogram(Dataset(dates, 'Date'), num_bins=4) plot = mpl_renderer.get_plot(hist) artist = plot.handles['artist'] ax = plot.handles['axis'] self.assertEqual(ax.get_xlim(), (736330.0, 736333.0)) self.assertEqual([p.get_x() for p in artist.patches], [736330.0, 736330.75, 736331.5, 736332.25])
def test_histogram_datetime64_plot(self): dates = np.array([dt.datetime(2017, 1, i) for i in range(1, 5)]) hist = histogram(Dataset(dates, 'Date'), num_bins=4) plot = mpl_renderer.get_plot(hist) artist = plot.handles['artist'] ax = plot.handles['axis'] self.assertEqual(ax.get_xlim(), (17167.0, 17170.0)) bounds = [17167.0, 17167.75, 17168.5, 17169.25] self.assertEqual([p.get_x() for p in artist.patches], bounds)
def filter_count(agg, min_count, **kwargs): if min_count: agg = deepcopy(agg) agg.data.Count.data[agg.data.Count.data < min_count] = 0 return agg def hline_fn(min_count, **kwargs): return hv.VLine(min_count) def tiles_fn(alpha, **kwargs): return tiles.opts(style=dict(alpha=alpha)) explorer = OSMExplorer(name="OpenStreetMap GPS Explorer") tile = hv.DynamicMap(tiles_fn, streams=[explorer]) agg = aggregate(hv.Points(df)) filtered = hv.util.Dynamic(agg, operation=filter_count, streams=[explorer]) shaded = shade(filtered, streams=[explorer]) hline = hv.DynamicMap(hline_fn, streams=[explorer]) explorer.output = (tile * shaded) << histogram(agg, log=True) * hline doc = parambokeh.Widgets(explorer, view_position='right', callback=explorer.event, mode='server')
shaded = datashade(points, cmap=colors.sequential.Plasma) # Create Tiles Element dispaying a mapbox light theme map tiles = hv.Tiles().opts(mapboxstyle="light", accesstoken=get_mapbox_token(), height=500, width=500, padding=0) # Create overlay of datashaded Scatter element on top of map map_overlay = tiles * shaded # Create Histogram Element hist = histogram(ds, dimension="fare_amount", normed=False, num_bins=20, bin_range=(0, 30.0)).opts(color=colors.qualitative.Plotly[0], height=500) # Build selection linking object that can be reused to link across plots lnk_sel = link_selections.instance() # Link selections across map overlay and histogram linked_map_overlay = lnk_sel(map_overlay) linked_hist = lnk_sel(hist) # Use plot hook to set the default histogram drag mode to box selection def set_dragmode(plot, element): fig = plot.state fig["layout"]["dragmode"] = "select"
def test_dynamic_operation_init_renamed_stream_params(self): img = Image(sine_array(0,5)) stream = RangeX(rename={'x_range': 'bin_range'}) histogram(img, bin_range=(0, 1), streams=[stream], dynamic=True) self.assertEqual(stream.x_range, (0, 1))
def test_dynamic_operation_init_stream_params(self): img = Image(sine_array(0,5)) stream = Stream.define('TestStream', bin_range=None)() histogram(img, bin_range=(0, 1), streams=[stream], dynamic=True) self.assertEqual(stream.bin_range, (0, 1))