def test_bars(scales): # Create a Bar chart with data of multiple shapes should work with binary serialization bars = bqplot.Bars(x=[0, 1], y=[[0, 1], [1, 0, -1]], scales=scales) bars = bqplot.Bars(x=[0, 1], y=[[1, 2], [3, 4]], scales=scales) state = bars.get_state() bars2 = bqplot.Bars(scales=scales) bars2.set_state(state) assert bars.x[0] == 0 assert bars.x[1] == 1 assert bars.y[0][0] == 1 assert bars.y[0][1] == 2 assert bars.y[1][0] == 3 assert bars.y[1][1] == 4
def test_bars(scales): with pytest.raises(TraitError, match='.*type object.*'): lines = bqplot.Bars(x=[0, 1], y=[[0, 1], [1, 0, -1]], scales=scales) lines = bqplot.Bars(x=[0, 1], y=[[1, 2], [3, 4]], scales=scales) state = lines.get_state() lines2 = bqplot.Lines(scales=scales) lines2.set_state(state) assert lines.x[0] == 0 assert lines.x[1] == 1 assert lines.y[0][0] == 1 assert lines.y[0][1] == 2 assert lines.y[1][0] == 3 assert lines.y[1][1] == 4
def test_bars(scales): with pytest.raises(ValueError, match='.*Unsupported dtype object*'): bars = bqplot.Bars(x=[0, 1], y=[[0, 1], [1, 0, -1]], scales=scales) bars = bqplot.Bars(x=[0, 1], y=[[1, 2], [3, 4]], scales=scales) state = bars.get_state() bars2 = bqplot.Bars(scales=scales) bars2.set_state(state) assert bars.x[0] == 0 assert bars.x[1] == 1 assert bars.y[0][0] == 1 assert bars.y[0][1] == 2 assert bars.y[1][0] == 3 assert bars.y[1][1] == 4
def create(self, data): size = data.shape[0] assert len(data.shape) == 1 xmin, xmax = self.limits[0] dx = (xmax - xmin) / size x = np.linspace(xmin, xmax - dx, size) + dx / 2 # print xmin, xmax, x self.scale_x = bq.LinearScale(min=xmin + dx / 2, max=xmax - dx / 2) self.scale_y = bq.LinearScale() self.axis_x = bq.Axis(label='X', scale=self.scale_x) self.axis_y = bq.Axis(label='Y', scale=self.scale_y, orientation='vertical') self.bars = bq.Bars(x=x, y=data, scales={ 'x': self.scale_x, 'y': self.scale_y }, colors=[self.color]) self.fig = bq.Figure(axes=[self.axis_x, self.axis_y], marks=[self.bars], padding_x=0)
def __init__(self, lineFig): """ """ self.lineFig = lineFig self.marks = self.lineFig.marks y_ord = bq.OrdinalScale() x_sc = bq.LinearScale() legendLabels = [] self.colours = [] for mark in self.marks: legendLabels += mark.labels self.colours += mark.colors[:len(mark.labels)] self.bars = bq.Bars( y=[1] * len(legendLabels), # all bars have a amplitude of 1 ## ? x=legendLabels, scales={ 'y': x_sc, 'x': y_ord }, colors=self.colours, padding=0.6, orientation='horizontal', stroke='white') ## remove the black border around the bar self.bars.opacities = [ScatLegend.OPAC_BRIGHT] * len(self.bars.x) ax_y = bq.Axis(scale=y_ord, orientation="vertical") ax_x = bq.Axis(scale=x_sc) ax_x.visible = False margin = dict(top=40, bottom=0, left=110, right=5) self.fig = bq.Figure(marks=[self.bars], axes=[ax_y, ax_x], fig_margin=margin) # Variable height depending on number of bars in legend self.fig.layout.height = str(45 + 20 * len(legendLabels)) + 'px' self.fig.layout.width = '170px' self.fig.min_aspect_ratio = 0.000000000001 # effectively remove aspect ratio constraint self.fig.max_aspect_ratio = 999999999999999 # effectively remove aspect ratio constraint self.fig.background_style = {'fill': 'White'} self.bars.on_element_click(self.changeOpacity)
def __init__(self, view, viewer_state, layer, layer_state): super(BqplotHistogramLayerArtist, self).__init__(layer) self.reset_cache() self.view = view self.state = layer_state or self._layer_state_cls( viewer_state=viewer_state, layer=self.layer) self._viewer_state = viewer_state if self.state not in self._viewer_state.layers: self._viewer_state.layers.append(self.state) self.bars = bqplot.Bars(scales=self.view.scales, x=[0, 1], y=[0, 1]) self.view.figure.marks = list(self.view.figure.marks) + [self.bars] link((self.state, 'color'), (self.bars, 'colors'), lambda x: [x], lambda x: x[0]) #link((self.bars, 'default_opacities'), (self.state, 'alpha'), lambda x: x[0], lambda x: [x]) #link((self.bars, 'default_size'), (self.state, 'size')) self._viewer_state.add_global_callback(self._update_histogram) self.state.add_global_callback(self._update_histogram) self.bins = None
def __init__(self, view, viewer_state, layer_state=None, layer=None): super(BqplotHistogramLayerArtist, self).__init__(viewer_state, layer_state=layer_state, layer=layer) self.view = view self.bars = bqplot.Bars(scales=self.view.scales, x=[0, 1], y=[0, 1]) self.view.figure.marks = list(self.view.figure.marks) + [self.bars] dlink((self.state, 'color'), (self.bars, 'colors'), lambda x: [color2hex(x)]) self._viewer_state.add_global_callback(self._update_histogram) self.state.add_global_callback(self._update_histogram) self.bins = None link((self.state, 'visible'), (self.bars, 'visible'))
def __init__(self, view, viewer_state, layer_state=None, layer=None): super(BqplotHistogramLayerArtist, self).__init__(viewer_state, layer_state=layer_state, layer=layer) self.view = view self.bars = bqplot.Bars(scales=self.view.scales, x=[0, 1], y=[0, 1]) self.view.figure.marks = list(self.view.figure.marks) + [self.bars] link((self.state, 'color'), (self.bars, 'colors'), lambda x: [x], lambda x: x[0]) #link((self.bars, 'default_opacities'), (self.state, 'alpha'), lambda x: x[0], lambda x: [x]) #link((self.bars, 'default_size'), (self.state, 'size')) self._viewer_state.add_global_callback(self._update_histogram) self.state.add_global_callback(self._update_histogram) self.bins = None link((self.state, 'visible'), (self.bars, 'visible'))
def __init__(self, output, presenter, **kwargs): self.output = output self.presenter = presenter super().__init__(zoom_y=False, **kwargs) self.bar = self.mark = bqplot.Bars(x=[1, 2], scales=self.scales, type='grouped') self.figure.marks = self.figure.marks + [self.mark]
def run_zonal_computation(aoi, output): aoi_model = aoi.view.model list_zones = get_ecozones() #get the aoi name aoi_name = aoi_model.name #create the result folder resultDir = os.path.join(os.path.expanduser('~'), 'zonal_results', aoi_name, '') os.makedirs(resultDir, exist_ok=True) #create the map Map = sm.SepalMap(['CartoDB.Positron']) ################################### ### placer sur la map #### ################################### output.add_live_msg('visualize data') aoi = aoi_model.feature_collection Map.addLayer(aoi, {}, 'aoi') Map.zoom_ee_object(aoi.geometry()) #add dataset dataset = ee.ImageCollection('NASA/MEASURES/GFCC/TC/v3').filter( ee.Filter.date('2010-01-01', '2010-12-31')) treeCanopyCover = dataset.select('tree_canopy_cover') treeCanopyCoverVis = { 'min': 0.0, 'max': 100.0, 'palette': ['ffffff', 'afce56', '5f9c00', '0e6a00', '003800'], } country_gfcc_2010 = treeCanopyCover.mean().clip(aoi) Map.addLayer(country_gfcc_2010, treeCanopyCoverVis, 'Tree Canopy Cover') #load the ecozones gez_2010 = ee.Image('users/bornToBeAlive/gez_2010_wgs84') country_gez_2010 = gez_2010.select('b1').clip(aoi) Map.addLayer(country_gez_2010.sldStyle(getSldStyle()), {}, 'gez 2010 raster') #show the 0 values cdl = country_gez_2010.select('b1') masked = ee.Image(cdl).updateMask(cdl.eq(0)) Map.addLayer(masked, {'palette': 'red'}, 'masked 0 data') #mask these values from the results country_gez_2010 = ee.Image(cdl).updateMask(cdl.neq(0)) #Get the list of values from the mosaic image freqHist = country_gez_2010.reduceRegions( **{ 'reducer': ee.Reducer.frequencyHistogram(), 'collection': aoi, 'scale': 100, }) #rewrite the dictionary values = ee.List( freqHist.map(getVal).aggregate_array('vals')).flatten().distinct() #Run reduceToVectors per class by masking all other classes. classes = country_gez_2010.reduceToVectors( **{ 'reducer': ee.Reducer.countEvery(), 'geometry': aoi, 'scale': 100, 'maxPixels': 1e10 }) country_gez_2010_vector = ee.FeatureCollection(classes) #add the borders on the map empty = ee.Image().byte() outline = empty.paint(**{ 'featureCollection': country_gez_2010_vector, 'color': 1, 'width': 1 }) Map.addLayer(outline, {'palette': '000000'}, 'gez 2010 borders') #export raw data out_dir = os.path.join(os.path.expanduser('~'), 'downloads') raw_stats = os.path.join(resultDir, aoi_name + '_raw.csv') if not os.path.isfile(raw_stats): output.add_live_msg('compute the zonal analysis') #compute the zonal analysis computation = False cpt = 0 while not computation: f = io.StringIO() with redirect_stdout(f): geemap.zonal_statistics(in_value_raster=country_gfcc_2010, in_zone_vector=country_gez_2010_vector, out_file_path=raw_stats, statistics_type='FIXED_HIST', scale=100, crs=getConformProj(), hist_min=0, hist_max=100, hist_steps=100, tile_scale=2**cpt) output.add_live_msg(f.getvalue()) #check if the computation have finished on a file if not os.path.isfile(raw_stats): #cannot use tile_scale > 16 if cpt == 3: raise Exception("Aoi is to big") #change the tile_scale and relaunch the process output.add_live_msg(f.getvalue(), 'error') time.sleep(2) cpt += 1 output.add_live_msg(f'Increasing tile_scale ({2**cpt})', 'warning') time.sleep(2) else: computation = True ####################################### ### lire et concatener les données ### ####################################### out_stats = os.path.join(resultDir, aoi_name + '_stats.csv') if not os.path.isfile(out_stats): output.add_live_msg('read and concatenate the data') data = pd.read_csv(raw_stats, sep=',') output.add_live_msg('remove no_data') #enlever les lignes Nan #(vérifier dans le tableau d'avant qu'elles ne sont pas trop grandes) data = data.dropna() #recuperer les valeurs de label ecozones = data.label.unique() output.add_live_msg('merge') #aggreger les lignes avec les même valeurs stats = pd.DataFrame([i for i in range(100)], columns=['treecover']) stats = stats.set_index('treecover') for _, ecozoneId in enumerate(ecozones): patches = data[data.label == ecozoneId] ecozone = get_ecozones()[ecozoneId] stats[ecozone] = 0 for index, patch in patches.iterrows(): tmp = pd.DataFrame( [val[1] for val in json.loads(patch['histogram'])]) stats[ecozone] = stats[ecozone] + tmp[0] stats = stats * 100 * 100 / 1e6 #exporter stats.to_csv(out_stats, index=True) ############################# ## create the layout ## ############################# output.add_live_msg('create the layout') stats = pd.read_csv(out_stats, index_col='treecover') #recuperer les noms de label ecozones = stats.columns x_sc = bq.LinearScale() ax_x = bq.Axis(label='treecover (%)', scale=x_sc) x = [] for i in range(100): x.append(i) figs = [] zones_id = [] for ecozone in ecozones: #get the # of the ecozone for index, value in get_ecozones().items(): if value == ecozone: zone_index = index zones_id.append(index) break y_sc = bq.LinearScale(max=stats[ecozone].max()) ax_y = bq.Axis(label='surface (Km\u00B2)', scale=y_sc, orientation='vertical') #, tick_format='.2e') y = [] for index, row in stats.iterrows(): y.append(row[ecozone]) mark = bq.Bars(x=x, y=y, scales={ 'x': x_sc, 'y': y_sc }, colors=[get_colors()[zone_index]], stroke='black', padding=0.1) fig_hist = bq.Figure(title=ecozone, marks=[mark], axes=[ax_x, ax_y]) figs.append(fig_hist) #add a coherent legend legend_keys = [get_ecozones()[i] for i in zones_id] legend_colors = [get_colors()[i] for i in zones_id] Map.add_legend(legend_keys=legend_keys, legend_colors=legend_colors, position='topleft') #create the partial layout children = [ v.Flex(xs12=True, class_='pa-0', children=[sw.DownloadBtn('Download .csv', path=out_stats)]), v.Flex(xs12=True, class_='pa-0', children=[Map]), v.Flex(xs12=True, class_='pa-0', children=figs) ] output.add_live_msg('complete', 'success') return children
# START OF ************************************************************************************************************** Build bar charts (use of bqp) *********************** x_ord = bqp.OrdinalScale() y_sc = bqp.LinearScale() y_sc.max = 1 #Plot #1 i.e. Creation of the bar plot bar = bqp.Bars( x=[], y=[], scales={ 'x': x_ord, 'y': y_sc }, orientation="horizontal", display_legend=True, labels=[ 'Initial Weights', 'Mkt Efficient Portfolio (Max Sharpe)', 'Efficient Portfolio with Views (BL)' ], #orientation decides whether the bars are horizontal or vertical colors=['#4fa110', '#1B84ED', '#F39F41'], opacities=[0.8, 0.9, 1], type='grouped') #bar.type='grouped' bar.tooltip = bqp.Tooltip( fields=['y'], labels=['Weight of Asset'], formats=['.3f']) #this displays the weight placed on each asset. ax_x = bqp.Axis(scale=x_ord, orientation="vertical") ax_y = bqp.Axis(scale=y_sc, label='Weight')
def create_viz(self): self.scales = {'x': self.x_scale, 'y': self.y_scale} self.bar = self.mark = bqplot.Bars(x=self.state.x_centers, y=self.state.grid, scales=self.scales) self.marks = [self.mark]