Beispiel #1
0
def test_LogColorMapper():
    mapper = LogColorMapper()
    yield (
        check_properties_existence,
        mapper,
        ["palette", "low", "high", "nan_color"],
    )
Beispiel #2
0
def get_color_mapper(column, df, palette='Viridis256'):
    '''
    Return a color mapper instace for a given category or continuous
    properties

    Args:
        column :  str
            name of the color that should be color mapped
        df : pandas.DataFrame
            data frame
    '''

    cmaps = {
        'block': 'Set1_4',
        'period': 'Dark2_7',
        'name_series': 'Spectral10',
        'group_name': viridis(18),
        'is_radioactive': d3['Category10'][4][2:],
        'is_monoisotopic': d3['Category10'][4][2:],
        'goldschmidt_class': 'Set2_4',
        'geochemical_class': d3['Category10'][10],
    }

    if column in cmaps.keys():
        factors = list(df[column].unique())
        if any(x is None for x in factors):
            factors = sorted([x for x in factors if x is not None]) + [None]
        elif column == 'group_name':
            factors = [
                str(x)
                for x in sorted(int(s) for s in factors if s != 'f block')
            ] + ['f block']
        else:
            factors = sorted(factors)
        ccm = CategoricalColorMapper(palette=cmaps[column],
                                     factors=factors,
                                     nan_color='#ffffff')
    elif column == 'value':

        if df[column].skew() > SKEW_THRS:
            ccm = LogColorMapper(palette=palette,
                                 low=df[column].min(),
                                 high=df[column].max(),
                                 nan_color='#ffffff')
        else:
            ccm = LinearColorMapper(palette=palette,
                                    low=df[column].min(),
                                    high=df[column].max(),
                                    nan_color='#ffffff')
    else:
        ccm = None

    return ccm
Beispiel #3
0
def get_color_mapper(column, df, palette="Viridis256"):
    """
    Return a color mapper instace for a given category or continuous
    properties

    Args:
        column :  str
            name of the color that should be color mapped
        df : pandas.DataFrame
            data frame
    """

    cmaps = {
        "block": "Set1_4",
        "period": "Dark2_7",
        "name_series": "Spectral10",
        "group_name": viridis(18),
        "is_radioactive": d3["Category10"][4][2:],
        "is_monoisotopic": d3["Category10"][4][2:],
        "goldschmidt_class": "Set2_4",
        "geochemical_class": d3["Category10"][10],
    }

    if column in cmaps.keys():
        factors = list(df[column].unique())
        if any(x is None for x in factors):
            factors = sorted([x for x in factors if x is not None]) + [None]
        elif column == "group_name":
            factors = [str(x) for x in sorted(int(s) for s in factors
                       if s != "f block")] + ["f block"]
        else:
            factors = sorted(factors)
        ccm = CategoricalColorMapper(palette=cmaps[column], factors=factors,
                                     nan_color="#ffffff")
    elif column == "value":

        if df[column].skew() > SKEW_THRS:
            ccm = LogColorMapper(palette=palette, low=df[column].min(),
                                 high=df[column].max(), nan_color="#ffffff")
        else:
            ccm = LinearColorMapper(palette=palette, low=df[column].min(),
                                    high=df[column].max(), nan_color="#ffffff")
    else:
        ccm = None

    return ccm
    def _set_video(self, vid_path: Union[Path, str]):
        self.tif = tifffile.TiffFile(vid_path)

        self.current_frame = 0
        self.frame = self.tif.asarray(key=self.current_frame)

        # this is basically used for vmin mvax
        self.color_mapper = LogColorMapper(
            palette=auto_colormap(256, 'gnuplot2', output='bokeh'),
            low=np.nanmin(self.frame),
            high=np.nanmax(self.frame)
        )

        self.image_glyph.data_source.data['image'] = [self.frame]
        self.image_glyph.glyph.color_mapper = self.color_mapper

        # shows the file size in gigabytes
        self.label_filesize.update(value=str(os.path.getsize(vid_path) / 1024 / 1024 / 1024))
def log_cmap(field_name,
             palette,
             low,
             high,
             low_color=None,
             high_color=None,
             nan_color="gray"):
    ''' Create a ``DataSpec`` dict to apply a client-side ``LogColorMapper``
    transformation to a ``ColumnDataSource`` column.

    Args:
        field_name (str) : a field name to configure ``DataSpec`` with

        palette (seq[color]) : a list of colors to use for colormapping

        low (float) : a minimum value of the range to map into the palette.
            Values below this are clamped to ``low``.

        high (float) : a maximum value of the range to map into the palette.
            Values above this are clamped to ``high``.

        low_color (color, optional) : color to be used if data is lower than
            ``low`` value. If None, values lower than ``low`` are mapped to the
            first color in the palette. (default: None)

        high_color (color, optional) : color to be used if data is higher than
            ``high`` value. If None, values higher than ``high`` are mapped to
            the last color in the palette. (default: None)

        nan_color (color, optional) : a default color to use when mapping data
            from a column does not succeed (default: "gray")

    '''
    return field(
        field_name,
        LogColorMapper(palette=palette,
                       low=low,
                       high=high,
                       nan_color=nan_color,
                       low_color=low_color,
                       high_color=high_color))
Beispiel #6
0
                tools=[hover, tap, zoom, pan])

plot.title.text = "VirtualDive"
plot.title.text_font_size = "25px"
plot.title_location = "right"
plot.title.align = "right"
plot.api_key = "AIzaSyAX0RhQ5JTdQAjveEADHzBXbxkVLYCiPps"

#color_mapper = CategoricalColorMapper(factors=['hi', 'lo'], palette=[RdBu3[2], RdBu3[0]])
#color_mapper = LogColorMapper(palette="Viridis5", low=min_median_house_value, high=max_median_house_value)

paletteinvert = palette[::-1]

color_mapper = CategoricalColorMapper(palette=["magenta", "cyan"],
                                      factors=['No', 'Yes'])
color_mapper2 = LogColorMapper(palette=fire)

protectedannulus = Annulus(x="lon",
                           y="lat",
                           inner_radius=4000,
                           outer_radius=7000,
                           fill_color="cyan",
                           fill_alpha=0.3,
                           line_color=None)

unprotectedannulus = Annulus(x="lon",
                             y="lat",
                             inner_radius=4000,
                             outer_radius=7000,
                             fill_color={
                                 'field': 'color',
TOOLS = "pan,wheel_zoom,reset,hover,save,tap"

# init figure
p = figure(title="Plotting USarray stations", 
           toolbar_location="left",  x_axis_label='Longitude', y_axis_label='Latitude', tools="lasso_select",plot_width=750, plot_height=500)

# Draw state lines
p.patches(state_xs, state_ys, fill_alpha=0.0,
    line_color="#884444", line_width=1.5)


# Now group these values together into a lists of x (longitude) and y (latitude)
x = locations["longitude"].tolist()
y = locations["latitude"].tolist()
custom_colors = ['#f2f2f2', '#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26']
color_mapper = LogColorMapper(palette=custom_colors)    

data = dict(x=x, y=y,
            rate=array_vals.iloc[0].tolist(),**d)
s1 = ColumnDataSource(data)

#creating stations over the map of United States
p.circle('x', 'y', source=s1,
          fill_color={'field': 'rate', 'transform': color_mapper},
          fill_alpha=2,size=7)

#Creating the spectrogram
sp = figure(title="Spectrogram", x_range=(0, 14401), y_range=(0, 438),x_axis_label='Time in seconds', y_axis_label='Stations by distance from origin',plot_width=450, plot_height=250)

sp.image(image=[h], x=0, y=0, dw=14401, dh=438, palette="Spectral11")
Beispiel #8
0
p_img.border_fill_alpha = 0.4
p_img.axis.major_tick_out = 0
p_img.axis.major_tick_in = 5
p_img.axis.minor_tick_out = 0
p_img.axis.minor_tick_in = 3
p_img.axis.major_tick_line_color = "white"
p_img.axis.minor_tick_line_color = "white"
if imgdict['observatory'] == 'SDO' and imgdict['instrument'] == 'AIA':
    palette = getAIApalette(wavelngth)
    colormap_jet = cm.get_cmap("jet")  # choose any matplotlib colormap here
    # palette = [colors.rgb2hex(m) for m in colormap_jet(np.arange(colormap_jet.N))]
    clrange = DButil.sdo_aia_scale_dict(wavelength=wavelngth,
                                        imagetype=imagetype)
    if clrange['log']:
        colormapper = LogColorMapper(palette=palette,
                                     low=clrange['low'],
                                     high=clrange['high'])
    else:
        colormapper = LinearColorMapper(palette=palette,
                                        low=clrange['low'],
                                        high=clrange['high'])
else:
    palette = bp.viridis(256)
    colormapper = LinearColorMapper(palette=palette)

r_img = p_img.image(image=[zz],
                    x=xbd[0],
                    y=ybd[0],
                    dw=xbd[-1] - xbd[0] + dx,
                    dh=ybd[-1] - ybd[0] + dy,
                    color_mapper=colormapper)
Beispiel #9
0
    def PlotMap(self,
                DrawLimb=True,
                DrawGrid=True,
                grid_spacing=15 * u.deg,
                ignore_coord=False,
                title=None,
                tools=None,
                x_range=None,
                y_range=None,
                palette=None,
                imagetype='image',
                *args,
                **kwargs):
        """Plot the map using the bokeh.plotting interface
        """

        source_image = self.ImageSource()
        if not title:
            title = self.smap.name

        if not tools:
            tools = 'pan,wheel_zoom,save,reset'
        if not x_range:
            x_range = self.x_range
        if not y_range:
            y_range = self.y_range

        if not palette:
            if self.smap.observatory == 'SDO' and self.smap.instrument[
                    0:3] == 'AIA':
                wavelngth = '{:.0f}'.format(self.smap.wavelength.value)
                # clmap = cm.get_cmap("sdoaia" + wavelngth)  # choose any matplotlib colormap here
                # palette = [colors.rgb2hex(m).encode("ascii").upper() for m in clmap(np.arange(clmap.N))]
                palette = getAIApalette(wavelngth)
                clrange = DButil.sdo_aia_scale_dict(wavelength=wavelngth,
                                                    imagetype=imagetype)
                print clrange
                if clrange['log']:
                    colormapper = LogColorMapper(palette=palette,
                                                 low=clrange['low'],
                                                 high=clrange['high'])
                else:
                    colormapper = LinearColorMapper(palette=palette,
                                                    low=clrange['low'],
                                                    high=clrange['high'])
            else:
                palette = bokehpalette_jet
                colormapper = LinearColorMapper(palette=palette)
        else:
            colormapper = LinearColorMapper(palette=palette)

        if ignore_coord:
            x_range = [0 - 0.5, self.smap.data.shape[0] + 0.5]
            y_range = [0 - 0.5, self.smap.data.shape[1] + 0.5]
            p_xaxis_visible = False
            p_yaxis_visible = False
            p_xaxis_axislabel = ''
            p_yaxis_axislabel = ''
            x0 = 0 - 0.5
            y0 = 0 - 0.5
            dw = self.smap.data.shape[0]
            dh = self.smap.data.shape[1]
        else:
            p_xaxis_visible = True
            p_yaxis_visible = True
            p_xaxis_axislabel = 'X-position [arcsec]'
            p_yaxis_axislabel = 'Y-position [arcsec]'
            x0 = self.x
            y0 = self.y
            dw = self.dw
            dh = self.dh

        p_image = figure(tools=tools,
                         x_range=x_range,
                         y_range=y_range,
                         title=title,
                         plot_height=self.plot_height,
                         plot_width=self.plot_width,
                         *args,
                         **kwargs)
        p_image.xaxis.axis_label = p_xaxis_axislabel
        p_image.yaxis.axis_label = p_yaxis_axislabel
        p_image.xaxis.visible = p_xaxis_visible
        p_image.yaxis.visible = p_yaxis_visible
        r_img = p_image.image(image=source_image['data'],
                              x=x0,
                              y=y0,
                              dw=dw,
                              dh=dh,
                              color_mapper=colormapper)
        if DrawLimb:
            p_image.line(x='x',
                         y='y',
                         line_color='white',
                         line_dash='solid',
                         source=self.DrawLimbSource())
            if DrawGrid:
                p_image.multi_line(
                    xs='xs',
                    ys='ys',
                    line_color='white',
                    line_dash='dotted',
                    source=self.DrawGridSource(grid_spacing=grid_spacing))
        return p_image, r_img
Beispiel #10
0
def map_tab(map_cov, map_df, min_density, max_density):

    # Input GeoJSON source that contains features for plotting.
    geosource = GeoJSONDataSource(geojson=map_cov)

    palette = RdYlGn[11]
    low = min_density
    high = max_density
    color_mapper = LogColorMapper(palette=palette,
                                  low=low,
                                  high=high,
                                  nan_color='whitesmoke',
                                  low_color='whitesmoke')

    #Create color bar.
    color_bar = ColorBar(color_mapper=color_mapper,
                         location=(0, 0),
                         orientation='horizontal',
                         ticker=LogTicker(),
                         border_line_color=None,
                         title='Density of confirmed cases')

    #Create figure object.
    p = figure(title='COVID-19 spread map',
               plot_height=900,
               plot_width=1500,
               toolbar_location='below',
               toolbar_sticky=False,
               background_fill_color="whitesmoke")
    p.title.text_font = "helvetica"
    p.title.text_font_size = "20px"
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    #Add patch renderer to figure.
    patches = p.patches('xs',
                        'ys',
                        source=geosource,
                        fill_color={
                            'field': 'ConfirmedDensity',
                            'transform': color_mapper
                        },
                        line_color='black',
                        line_width=0.25,
                        fill_alpha=0.5)

    p.renderers.append(patches)
    #Specify figure layout.
    p.add_layout(color_bar, 'below')

    #create hoover
    hover = HoverTool(tooltips=[('Country', '@{NAME_EN}'),
                                ('Population', '@Population'),
                                ('Confirmed', '@Confirmed'),
                                ('Deaths', '@Deaths'),
                                ('Recovered', '@Recovered'),
                                ('Conf. density', '@ConfirmedDensity'),
                                ('Deaths density', '@DeathsDensity'),
                                ('Recovered density', '@RecoveredDensity')],
                      renderers=[patches])
    p.add_tools(hover)

    # Input coronavirus data
    pointsource = ColumnDataSource(map_df)

    # color palette
    # palette_p = brewer['Blues'][9]
    # palette_p = palette_p[::-1]
    # palette_p[1::]
    # color_mapper_p = LinearColorMapper(palette=palette_p, low=0, high=17)

    # add points virus
    point = p.circle(
        'Long',
        'Lat',
        source=pointsource,
        size='Size',
        #color={'field': 'Size','transform': color_mapper_p},
        color='lightskyblue',
        fill_alpha=0.3,
        line_alpha=0.3)

    p.renderers.append(point)
    # create hoover
    hover_p = HoverTool(tooltips=[('Country', '@{Country/Region}'),
                                  ('Province', '@{Province/State}'),
                                  ('Confirmed', '@Confirmed'),
                                  ('Deaths', '@Deaths'),
                                  ('Recovered', '@Recovered')],
                        renderers=[point])
    p.add_tools(hover_p)

    # Add legend at fixed positions
    location, orientation, side = 'bottom_left', "horizontal", "center"
    legend = Legend(items=[("Nr. of confirmed cases", [point])],
                    location=location,
                    orientation=orientation,
                    border_line_color="black",
                    background_fill_alpha=0,
                    border_line_alpha=0)
    p.add_layout(legend, side)

    # Layout setup
    layout = p
    tab = Panel(child=layout, title='COVID-19 Map')

    return tab