Exemplo n.º 1
0
def beta_plot(fig, ax, data, params, direction, depth=None, cax=None, fontsize=None, mccomas=False, limits=None, refinement=0, titlesize=25, labelsize=20, ticklabelsize=15, skip_labeling=False, cbar_orientation='vertical'):
    X, Y, dslice = plot_setup(ax, data, params, direction, depth, fontsize=fontsize, mccomas=mccomas, titlesize=titlesize, labelsize=labelsize, ticklabelsize=ticklabelsize, skip_labeling=skip_labeling)

    if limits is None:
        limits = (-1,2)

    # Setup custom colorbar
    levels = np.logspace(limits[0] - .5,limits[1] + .5, (limits[1]-limits[0]+1)*(refinement+1)+1)
    ticks = np.logspace(limits[0],limits[1],limits[1]-limits[0]+1)
    viridis = cm.get_cmap('viridis', len(levels)+2)
    cmap = ListedColormap(viridis.colors[1:-1],'beta_cmap')
    cmap.set_over(viridis.colors[-1])
    cmap.set_bad(viridis.colors[0])

    # Catch the stupid warnings I don't care about
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')

        mappable = ax.contourf(X.T, Y.T, dslice, levels=levels, norm=MyLogNorm(),
                                cmap=cmap, extend='both',
                                vmin=levels[0], vmax=levels[-1])

    if cax != 'None':
        cb = fig.colorbar(mappable, ax=ax, cax=cax, orientation=cbar_orientation)
        cb.set_ticks(ticks)
        cb.set_ticklabels(ticks)

    return mappable, X, Y, dslice
Exemplo n.º 2
0
def rgb2cmap(filename, base='255'):
    """Function to read a rgb file (i.e. NCL colortables) and convert it
     to matplotlib colormap
     Author: Daniel Argueso @ CCRC, UNSW. Sydney (Australia)
    """

    from matplotlib.colors import ListedColormap
    import re

    filein = open(filename)
    lines = filein.readlines()
    colors = []

    for line in lines[2:]:
        line = re.sub('\s+', ' ', line)
        li = line.strip()
        if li:
            values = li.split(' ')
            if base == '255':
                new_values = [i / 255. for i in map(int, values[:3])]
            else:
                new_values = [i for i in map(float, values[:3])]
            colors.append(new_values)
    cmap = ListedColormap(colors)
    cmap.set_over(colors[-1])
    cmap.set_under(colors[0])

    return cmap
Exemplo n.º 3
0
def plot():
    """Do plotting work"""
    cmap1 = plt.get_cmap('inferno_r')
    colors = list(cmap1(np.arange(10) / 10.))
    cmap2 = plt.get_cmap('Pastel1')
    colors.extend(list(cmap2(np.arange(2) / 2.)))
    cmap = ListedColormap(colors)
    
    cmap.set_under('tan')
    cmap.set_over('white')
    minval = np.load('minval.npy')
    maxval = np.load('maxval.npy')
    diff = maxval - minval
    lons = np.load('lons.npy')
    lats = np.load('lats.npy')
    mp = MapPlot(sector='midwest', statebordercolor='white',
                 title=(r"Diff between coldest wind chill and warmest "
                        "air temp 29 Jan - 3 Feb 2019"),
                 subtitle=("based on hourly NCEP Real-Time Mesoscale Analysis "
                           "(RTMA) ending midnight CST"))

    levels = list(range(0, 101, 10))
    levels.extend([105, 110])
    mp.pcolormesh(lons, lats, diff, levels,
                  cmap=cmap, clip_on=False,
                  units=r"$^\circ$F", spacing='proportional')
    mp.postprocess(filename='test.png')
Exemplo n.º 4
0
def main():
    """
    Plot the data using the row_labels as, you guessed it, row labels and the data_dict as columns.
    The plot will be saved as input_file.png with the previous extension removed.
    """

    input_file = sys.argv[1]

    row_labels, data_dict = ParseFile(input_file)  # Get the data needed.

    df = pd.DataFrame(data_dict, index=row_labels)  # Create the dataframe.
    # EDIT THIS TO CHANGE FIGURE SIZE.
    plt.figure(figsize=(8, 11), dpi=1200)
    # Set colors [-5 to 5]. Can use html hex codes, recognized html colors, or rgb triplets.
    colors = ['#8c510a', "#bf812d", "#f5f5f5",
              "#f5f5f5", "#80cdc1", "#01665e"]
    cmap = ListedColormap(colors, name="cmap", N=6)  # Change N if you have a greater range.

    # Set colors for over/under the bound limits.
    cmap.set_over("#003c30")
    cmap.set_under("#543005")
    bounds = [-20, -10, -3, 0, 3, 10, 20]
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    # Create the plot without y axis labels. Change 'extend' to 'both' or 'min' to make cbar extend
    # in opposite direction.
    heatmap = sns.heatmap(df, cbar=True, cbar_kws={'extend':'max'} ,cmap=cmap, norm=norm, yticklabels=False)
    plt.xticks(rotation=90)
    plt.title(input_file.split(".")[0])

    out_name = input_file.split(".")[0] + ".pdf"  # EDIT extension to change output format.
    heatmap.figure.savefig(out_name)
Exemplo n.º 5
0
def pycmap(gacmap):
    from matplotlib.colors import ListedColormap
    from numpy import vstack
    r = gacmap.table['r']
    g = gacmap.table['g']
    b = gacmap.table['b']
    rt = ListedColormap(vstack((r, g, b)).T)
    rt.set_over((r[-1], g[-1], b[-1]))
    rt.set_under((r[0], g[0], b[0]))
    rt.set_bad(color='k', alpha=0)
    return rt
Exemplo n.º 6
0
def pycmap(gacmap):
  from matplotlib.colors import ListedColormap
  from numpy import vstack
  r = gacmap.table['r']
  g = gacmap.table['g']
  b = gacmap.table['b']
  rt = ListedColormap(vstack((r, g, b)).T)
  rt.set_over((r[-1], g[-1], b[-1]))
  rt.set_under((r[0], g[0], b[0]))
  rt.set_bad(color='k', alpha=0)
  return rt
Exemplo n.º 7
0
    def create_colormap(self, ticks, prec=1e-6):
        ncolor_p = len(np.where(ticks >  prec)[0]) + 1  # including zero
        ncolor_n = len(np.where(ticks < -prec)[0]) + 1  # including zero

        colors_interpolated_p = create_colors_interpolated(self._colors_p, ncolor_p)
        colors_interpolated_n = create_colors_interpolated(self._colors_n, ncolor_n)
        colors = np.vstack((
            colors_interpolated_n,
            colors_interpolated_p,
        ))
        colors = convert_white_to_transparent(colors)

        print("colors:")
        print(colors)

        cmap = ListedColormap(colors[1:-1])
        cmap.set_under(colors[ 0])
        cmap.set_over (colors[-1])
        return cmap
Exemplo n.º 8
0
def build_palette4(l1, l2, l3, l4):
    levs = l1 + l2 + l3 + l4

    cm1 = LinearSegmentedColormap.from_list("", ["#000080", "#00b2ee"])
    cm2 = LinearSegmentedColormap.from_list("", ["#ffff00", "#ff0000"])
    cm3 = LinearSegmentedColormap.from_list("", ["#ff0000", "#bebebe"])
    cm4 = LinearSegmentedColormap.from_list("", ["#bebebe", "#ffffff"])

    cl1 = cm1(np.linspace(0, 1., len(l1) + 1, endpoint=True))
    cl2 = cm2(np.linspace(0, 1., len(l2), endpoint=False))
    cl3 = cm3(np.linspace(0, 1., len(l3), endpoint=False))
    cl4 = cm4(np.linspace(0, 1., len(l4), endpoint=True))

    rgb = np.vstack([cl1, cl2, cl3, cl4])

    cmap = ListedColormap(rgb[1:-1], name="Caliop")
    norm = BoundaryNorm(levs, ncolors=len(levs) - 1, clip=False)
    cmap.set_under(rgb[0])
    cmap.set_over(rgb[-1])
    return cmap, norm
Exemplo n.º 9
0
    def create_colormap(self, ticks, prec=1e-6):
        ncolor_p = len(np.where(ticks > prec)[0]) + 1  # including zero
        ncolor_n = len(np.where(ticks < -prec)[0]) + 1  # including zero

        colors_interpolated_p = create_colors_interpolated(
            self._colors_p, ncolor_p)
        colors_interpolated_n = create_colors_interpolated(
            self._colors_n, ncolor_n)
        colors = np.vstack((
            colors_interpolated_n,
            colors_interpolated_p,
        ))
        colors = convert_white_to_transparent(colors)

        print("colors:")
        print(colors)

        cmap = ListedColormap(colors[1:-1])
        cmap.set_under(colors[0])
        cmap.set_over(colors[-1])
        return cmap
Exemplo n.º 10
0
def main():
    figure = plt.figure()
    basemap, lons2d, lats2d = get_basemap_and_coords()

    lons2d[lons2d > 180] -= 360

    x0, y0 = basemap(lons2d, lats2d)
    dx = x0[1, 0] - x0[0, 0]
    dy = y0[0, 1] - y0[0, 0]
    x1 = x0 - dx / 2.0
    y1 = y0 - dy / 2.0

    permafrost_kind_field = get_permafrost_mask(lons2d, lats2d)

    cmap = ListedColormap(["r", "b", "y", "c"])
    cmap.set_over("w")
    cmap.set_under("w")

    # permafrost_kind_field = np.ma.masked_where(permafrost_kind_field == 0, permafrost_kind_field)

    ax_map = plt.gca()
    # img = basemap.pcolormesh(x1, y1, permafrost_kind_field, ax = ax_map, vmin = 0.5, vmax = 4.5, cmap = cmap )
    permafrost_kind_field = maskoceans(lons2d, lats2d, permafrost_kind_field)

    img = basemap.contourf(x0, y0, permafrost_kind_field, levels=np.arange(0.5, 5, 0.5), cmap=cmap)

    divider = make_axes_locatable(ax_map)
    cax = divider.append_axes("bottom", "5%", pad="3%")
    cb = plt.colorbar(img, ticks=MultipleLocator(), cax=cax, orientation="horizontal")

    basemap.contour(x0, y0, permafrost_kind_field, ax=ax_map,
                    levels=list(range(6)), linewidths=0.5, colors="k")
    basemap.drawcoastlines(ax=ax_map)
    plt.savefig("test.png")

    # gdal.Dataset.
    # TODO: implement
    pass
Exemplo n.º 11
0
    def create_colormap_old_2(self, values, prec=1e-6):
        color_p = self._color_p
        color_n = self._color_n
        ncolor_p = len(np.where(values > prec)[0])
        ncolor_n = len(np.where(values < -prec)[0])

        color_list_0 = np.array([[0.0, 0.0, 0.0, 0.0]])
        color_list_n = self.create_color_list(color_n, ncolor_n)
        color_list_n = color_list_n[::-1]
        color_list_n = np.vstack((color_list_n, color_list_0))
        color_list_p = self.create_color_list(color_p, ncolor_p)
        color_list_p = np.vstack((color_list_0, color_list_p))

        color_list = np.vstack((color_list_n, color_list_p))
        color_list = self.convert_white_to_transparent(color_list)

        print("color_list:")
        print(color_list)

        cmap = ListedColormap(color_list[1:-1])
        cmap.set_under(color_list[0])
        cmap.set_over(color_list[-1])
        return cmap
Exemplo n.º 12
0
    def create_colormap_old_2(self, values, prec=1e-6):
        color_p = self._color_p
        color_n = self._color_n
        ncolor_p = len(np.where(values >  prec)[0])
        ncolor_n = len(np.where(values < -prec)[0])

        color_list_0 = np.array([[0.0, 0.0, 0.0, 0.0]])
        color_list_n = self.create_color_list(color_n, ncolor_n)
        color_list_n = color_list_n[::-1]
        color_list_n = np.vstack((color_list_n, color_list_0))
        color_list_p = self.create_color_list(color_p, ncolor_p)
        color_list_p = np.vstack((color_list_0, color_list_p))

        color_list = np.vstack((color_list_n, color_list_p))
        color_list = self.convert_white_to_transparent(color_list)

        print("color_list:")
        print(color_list)

        cmap = ListedColormap(color_list[1:-1])
        cmap.set_under(color_list[0])
        cmap.set_over(color_list[-1])
        return cmap
Exemplo n.º 13
0
def main():
    """
    Plot the data using the row_labels as, you guessed it, row labels and the data_dict as columns.
    The plot will be saved as input_file.png with the previous extension removed.
    """

    input_file = sys.argv[1]

    row_labels, data_dict = ParseFile(input_file)  # Get the data needed.

    df = pd.DataFrame(data_dict, index=row_labels)  # Create the dataframe.
    # EDIT THIS TO CHANGE FIGURE SIZE.
    plt.figure(figsize=(8, 11), dpi=1200)
    # Set colors [-5 to 5]. Can use html hex codes, recognized html colors, or rgb triplets.
    colors = ['#8c510a', "#bf812d", "#f5f5f5", "#f5f5f5", "#80cdc1", "#01665e"]
    cmap = ListedColormap(colors, name="cmap",
                          N=6)  # Change N if you have a greater range.

    # Set colors for over/under the bound limits.
    cmap.set_over("#003c30")
    cmap.set_under("#543005")
    bounds = [-20, -10, -3, 0, 3, 10, 20]
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    # Create the plot without y axis labels. Change 'extend' to 'both' or 'min' to make cbar extend
    # in opposite direction.
    heatmap = sns.heatmap(df,
                          cbar=True,
                          cbar_kws={'extend': 'max'},
                          cmap=cmap,
                          norm=norm,
                          yticklabels=False)
    plt.xticks(rotation=90)
    plt.title(input_file.split(".")[0])

    out_name = input_file.split(
        ".")[0] + ".pdf"  # EDIT extension to change output format.
    heatmap.figure.savefig(out_name)
Exemplo n.º 14
0
def tolnet_colormap():
    from matplotlib.colors import ListedColormap
    from numpy import array

    Colors = [
        array([255, 140, 255]) / 255.0,
        array([221, 111, 242]) / 255.0,
        array([187, 82, 229]) / 255.0,
        array([153, 53, 216]) / 255.0,
        array([119, 24, 203]) / 255.0,
        array([0, 0, 187]) / 255.0,
        array([0, 44, 204]) / 255.0,
        array([0, 88, 221]) / 255.0,
        array([0, 132, 238]) / 255.0,
        array([0, 175, 255]) / 255.0,
        array([0, 235, 255]) / 255.0,
        array([39, 255, 215]) / 255.0,
        array([99, 255, 155]) / 255.0,
        array([163, 255, 91]) / 255.0,
        array([211, 255, 43]) / 255.0,
        array([255, 255, 0]) / 255.0,
        array([255, 207, 0]) / 255.0,
        array([255, 159, 0]) / 255.0,
        array([255, 111, 0]) / 255.0,
        array([255, 63, 0]) / 255.0,
        array([255, 0, 0]) / 255.0,
        array([216, 0, 15]) / 255.0,
        array([178, 0, 31]) / 255.0,
        array([140, 0, 47]) / 255.0,
        array([102, 0, 63]) / 255.0,
        array([52, 52, 52]) / 255.0,
        array([96, 96, 96]) / 255.0,
        array([140, 140, 140]) / 255.0,
        array([184, 184, 184]) / 255.0,
        array([228, 228, 228]) / 255.0,
        [1.0, 1.0, 1.0],
    ]
    #     Colors = [
    #         array([255, 140, 255]) / 255.,
    #         array([221, 111, 242]) / 255.,
    #         array([187, 82, 229]) / 255.,
    #         array([153, 53, 216]) / 255.,
    #         array([119, 24, 203]) / 255.,
    #         array([0, 0, 187]) / 255.,
    #         array([0, 44, 204]) / 255.,
    #         array([0, 88, 221]) / 255.,
    #         array([0, 132, 238]) / 255.,
    #         array([0, 175, 255]) / 255.,
    #         array([0, 235, 255]) / 255.,
    #         array([39, 255, 215]) / 255.,
    #         array([99, 255, 155]) / 255.,
    #         array([163, 255, 91]) / 255.,
    #         array([211, 255, 43]) / 255.,
    #         array([255, 255, 0]) / 255.,
    #         array([255, 207, 0]) / 255.,
    #         array([255, 159, 0]) / 255.,
    #         array([255, 111, 0]) / 255.,
    #         array([255, 63, 0]) / 255.,
    #         array([255, 0, 0]) / 255.,
    #         array([216, 0, 15]) / 255.,
    #         array([178, 0, 31]) / 255.,
    #         array([140, 0, 47]) / 255.,
    #         array([102, 0, 63]) / 255.,
    #         array([52, 52, 52]) / 255.,
    #         array([52, 52, 52]) / 255.,
    #         array([52, 52, 52]) / 255.,
    #         array([52, 52, 52]) / 255.,
    #         array([52, 52, 52]) / 255.,
    #         array([52, 52, 52]) / 255.,
    #         array([96, 96, 96]) / 255.,
    #         array([96, 96, 96]) / 255.,
    #         array([96, 96, 96]) / 255.,
    #         array([96, 96, 96]) / 255.,
    #         array([96, 96, 96]) / 255.,
    #         array([96, 96, 96]) / 255.
    #     ]
    TNcmap = ListedColormap(Colors)
    TNcmap.set_under([1, 1, 1])
    TNcmap.set_over([0, 0, 0])
    return TNcmap
Exemplo n.º 15
0
mdata = maskoceans(lons, lats, dura)
m.drawcoastlines()
m.drawcounties(linewidth=0.4)

parallels = np.arange(0., 90, 0.1)
m.drawparallels(parallels,
                labels=[1, 0, 0, 0],
                dashes=[2, 900],
                fontsize=10,
                linewidth=0.4)
meridians = np.arange(180., 360., 0.2)
m.drawmeridians(meridians,
                labels=[0, 0, 0, 1],
                dashes=[2, 900],
                fontsize=10,
                linewidth=0.4)

cMAP = ListedColormap([
    '#00bfff', '#00ffff', '#009933', '#33cc33', '#c6ff1a', '#ffff00',
    '#ffcc00', '#ffcc00', '#ffcc00', '#ff9933', '#ff9933', '#ff9933',
    '#ff8000', '#ff8000', '#ff8000', '#ff6600', '#ff6600', '#ff6600',
    '#ff4000', '#ff4000', '#ff4000'
])
cMAP.set_under('#0080ff')
cMAP.set_over('#cc0000')
clevs = np.arange(6, 28, 1)
cs = m.contourf(x, y, mdata, clevs, cmap=cMAP, extend="both")
cbar = m.colorbar(cs, "right", size="5%", pad='2%')
cbar.set_label('Duration (days/event)')
plt.show()
Exemplo n.º 16
0
plt.close('all')
fig,ax=plt.subplots(1,1)
ax.hist(phase_rot.ravel())
ax.set_title('Gridded: Mask - 0 = Cloud,1 = 66% prob.\n Clear,2 = 95% prob. Clear,3 = 99% prob. Clear')


# In[112]:

plt.close('all')
from matplotlib.colors import Normalize
from numpy import ma
fig,ax=plt.subplots(1,1,figsize=(12,12))
colors=sns.color_palette('coolwarm')
pal=LinearSegmentedColormap.from_list('test',colors)
pal.set_bad('0.75') #75% grey
pal.set_over('r')
pal.set_under('k')
vmin= -5.
vmax= 5.
ch29 = np.rot90(file_dict['ch29'],2)
ch31 = np.rot90(file_dict['ch31'],2)
the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False)
tdiff= ch31 - ch29
tdiff=ma.array(tdiff,mask=np.isnan(tdiff))
CS= ax.imshow(tdiff,cmap=pal,norm=the_norm)
cax=plt.colorbar(CS,  ax = ax,extend='both')
cax.set_label('ch31 - ch29 brightnes temp (K)')
ax.set_title('TB 11 micron - TB 8 micron')


Exemplo n.º 17
0
def colour_map(colours, match_colour=None, match_value=None, dmin=None, 
                dmax=None, data=None, cmap_len=256, extend='neither'):
    """
    Return a matplotlib colour map from a list of colours. A single colour 
    within the list can be assigned a value by providing the data limits that 
    the colour map will be used on. Note, if using this functionality, 
    match_colour, match_value and data limits (or all the data) must be 
    provided.
    
    Args:
    
    * colours: list
        A list of matplotlib accepted colours. These include names (see 
        http://www.w3schools.com/html/html_colornames.asp), html hex colour 
        codes and RGB arrays.
    
    Kwargs:
    
    * match_colour: string or RBG array
        Specify one of the colours in the colour list (but not the first or 
        last) to be matched against a given value (see below).
    
    * match_value: float
        Specify a value to which a given colour is to be matched.
    
    * dmin: float
        Data minimum.
    
    * dmax: 
        Data maximum
        
    * data: array like
        Alternative to providing the limits. Limits are calculated using the 
        data within the function.
    
    * cmap_len: integer
        Total number of colours in the colour map.
    
    * extend: 'neither' or 'both'
        If 'both', the first and last colours are set to under and over data
        range colours.
    
    Returns:
        matplotlib.colors.Colormap
    
    """
    cmap = LinearSegmentedColormap.from_list('cmap', colours, N=cmap_len)
    if match_colour is not None:       
        assert match_value is not None, 'A value must be given with which to '\
        'match the colour.'
        colours = [colour.lower() for colour in colours]
        match_colour = match_colour.lower()
        assert match_colour in colours, 'The colour to match, %s, is not in'\
        ' the given colours list, %s.' % (match_colour, colours)
        if dmin is None or dmax is None:
            assert data is not None, 'To scale the colour map, data or data '\
            'minimum and maximum must be provided.'
            dmin = numpy.min(data)
            dmax = numpy.max(data)
        else:
            assert dmin is not None and dmax is not None, 'Both dmin and dmax'\
            ' must be provided.'
            assert dmin < dmax, 'dmin must be smaller than dmax.'
        
        assert dmin <= match_value <= dmax, 'match_value, %s, value must fall'\
        ' within the data range, %s & %s.' % (match_value, dmin, dmax) 
                                      
        colour_position = float(colours.index(match_colour)) / \
                          float(len(colours) - 1)
        if colour_position in [0., 1]:
            raise UserWarning('The colour to match the value cannot be a '\
                              'colour on the limits of the colour map.')
        value_position = float(match_value - dmin) / \
                               float(dmax - dmin)
                               
        if value_position > colour_position:
            # Cut off the top end of the colour map using equation...
            x = (colour_position * cmap.N) / value_position
            # Take colours from 0 to x (+1 for range to reach x value)
            colour_RGBs = cmap(range(int(round(x + 1))))
            cmap = ListedColormap(colour_RGBs)
        elif value_position < colour_position:
            # Cut off the bottom end of the colour map using equation...
            x = ((colour_position - value_position) * cmap.N) / \
                 (1. - value_position)
            # Take colours from x to end colour index (+1 for range to reach x 
            # value)
            colour_RGBs = cmap(range(int(round(x)), (cmap.N + 1)))
            cmap = ListedColormap(colour_RGBs)
    else:
        assert match_value is None, 'A value has been specified without a '\
        'colour to match it with.'
    if extend == 'both':
        over_colour = cmap(cmap.N)
        under_colour = cmap(0)
        colour_RGBs = cmap(range(1, cmap.N - 1))
        cmap = ListedColormap(colour_RGBs)
        cmap.set_over(over_colour)
        cmap.set_under(under_colour)
        
    return cmap
Exemplo n.º 18
0
a.loc["one", 5:7]
b = make_tuple(a)
a.one


# In[40]:

plt.close("all")
from matplotlib.colors import Normalize
from numpy import ma

fig, ax = plt.subplots(1, 1, figsize=(12, 12))
colors = sns.color_palette("coolwarm")
pal = LinearSegmentedColormap.from_list("test", colors)
pal.set_bad("0.75")  # 75% grey
pal.set_over("r")
pal.set_under("k")
vmin = -5.0
vmax = 5.0
ch29 = np.rot90(file_dict["ch29"], 2)
ch31 = np.rot90(file_dict["ch31"], 2)
the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
tdiff = ch29 - ch31
tdiff = ma.array(tdiff, mask=np.isnan(tdiff))
CS = ax.imshow(tdiff, cmap=pal, norm=the_norm)
cax = plt.colorbar(CS, ax=ax, extend="both")
cax.set_label("ch29 - ch31 brightnes temp (K)")
ax.set_title("TB 8 micron - TB 11 micron")


# ### For next Tuesday: check in a notebook that
Exemplo n.º 19
0
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth, alpha, **options):
    r"""
    ``region_plot`` takes a boolean function of two variables, `f(x,y)`
    and plots the region where f is True over the specified
    ``xrange`` and ``yrange`` as demonstrated below.

    ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)``

    INPUT:

    - ``f`` -- a boolean function or a list of boolean functions of two variables

    - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple
      ``(x,xmin,xmax)``

    - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple
      ``(y,ymin,ymax)``

    - ``plot_points``  -- integer (default: 100); number of points to plot
      in each direction of the grid

    - ``incol`` -- a color (default: ``'blue'``), the color inside the region

    - ``outcol`` -- a color (default: ``None``), the color of the outside
      of the region

    If any of these options are specified, the border will be shown as indicated,
    otherwise it is only implicit (with color ``incol``) as the border of the
    inside of the region.

     - ``bordercol`` -- a color (default: ``None``), the color of the border
       (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``)

    - ``borderstyle``  -- string (default: 'solid'), one of ``'solid'``,
      ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``,
      ``'--'``, ``':'``, ``'-.'``.

    - ``borderwidth``  -- integer (default: None), the width of the border in pixels

    - ``alpha`` -- (default: 1) How transparent the fill is. A number between 0 and 1.

    - ``legend_label`` -- the label for this item in the legend

    - ``base`` - (default: 10) the base of the logarithm if
      a logarithmic scale is set. This must be greater than 1. The base
      can be also given as a list or tuple ``(basex, basey)``.
      ``basex`` sets the base of the logarithm along the horizontal
      axis and ``basey`` sets the base along the vertical axis.

    - ``scale`` -- (default: ``"linear"``) string. The scale of the axes.
      Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``,
      ``"semilogy"``.

      The scale can be also be given as single argument that is a list
      or tuple ``(scale, base)`` or ``(scale, basex, basey)``.

      The ``"loglog"`` scale sets both the horizontal and vertical axes to
      logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis
      to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis
      to logarithmic scale. The ``"linear"`` scale is the default value
      when :class:`~sage.plot.graphics.Graphics` is initialized.


    EXAMPLES:

    Here we plot a simple function of two variables::

        sage: x,y = var('x,y')
        sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3))
        Graphics object consisting of 1 graphics primitive

    Here we play with the colors::

        sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray')
        Graphics object consisting of 2 graphics primitives

    An even more complicated plot, with dashed borders::

        sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250)
        Graphics object consisting of 2 graphics primitives

    A disk centered at the origin::

        sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1))
        Graphics object consisting of 1 graphics primitive

    A plot with more than one condition (all conditions must be true for the statement to be true)::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2))
        Graphics object consisting of 1 graphics primitive

    Since it doesn't look very good, let's increase ``plot_points``::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400)
        Graphics object consisting of 1 graphics primitive

    To get plots where only one condition needs to be true, use a function.
    Using lambda functions, we definitely need the extra ``plot_points``::

        sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400)
        Graphics object consisting of 1 graphics primitive

    The first quadrant of the unit circle::

        sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400)
        Graphics object consisting of 1 graphics primitive

    Here is another plot, with a huge border::

        sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50)
        Graphics object consisting of 2 graphics primitives

    If we want to keep only the region where x is positive::

        sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50)
        Graphics object consisting of 1 graphics primitive

    Here we have a cut circle::

        sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200)
        Graphics object consisting of 2 graphics primitives

    The first variable range corresponds to the horizontal axis and
    the second variable range corresponds to the vertical axis::

        sage: s,t=var('s,t')
        sage: region_plot(s>0,(t,-2,2),(s,-2,2))
        Graphics object consisting of 1 graphics primitive

    ::

        sage: region_plot(s>0,(s,-2,2),(t,-2,2))
        Graphics object consisting of 1 graphics primitive

    An example of a region plot in 'loglog' scale::

        sage: region_plot(x^2+y^2<100, (x,1,10), (y,1,10), scale='loglog')
        Graphics object consisting of 1 graphics primitive

    TESTS:

    To check that :trac:`16907` is fixed::

        sage: x, y = var('x, y')
        sage: disc1 = region_plot(x^2+y^2 < 1, (x, -1, 1), (y, -1, 1), alpha=0.5)
        sage: disc2 = region_plot((x-0.7)^2+(y-0.7)^2 < 0.5, (x, -2, 2), (y, -2, 2), incol='red', alpha=0.5)
        sage: disc1 + disc2
        Graphics object consisting of 2 graphics primitives

    To check that :trac:`18286` is fixed::
        sage: x, y = var('x, y')
        sage: region_plot([x == 0], (x, -1, 1), (y, -1, 1))
        Graphics object consisting of 1 graphics primitive
        sage: region_plot([x^2+y^2==1, x<y], (x, -1, 1), (y, -1, 1))
        Graphics object consisting of 1 graphics primitive

    """

    from sage.plot.all import Graphics
    from sage.plot.misc import setup_for_eval_on_grid
    from sage.symbolic.expression import is_Expression
    from warnings import warn
    import numpy

    if not isinstance(f, (list, tuple)):
        f = [f]

    feqs = [equify(g) for g in f if is_Expression(g) and g.operator() is operator.eq and not equify(g).is_zero()]
    f = [equify(g) for g in f if not (is_Expression(g) and g.operator() is operator.eq)]
    neqs = len(feqs)
    if neqs > 1:
        warn("There are at least 2 equations; If the region is degenerated to points, plotting might show nothing.")
        feqs = [sum([fn**2 for fn in feqs])]
        neqs = 1
    if neqs and not bordercol:
        bordercol = incol
    if not f:
        return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points, fill=False, \
                             linewidth=borderwidth, linestyle=borderstyle, color=bordercol, **options)
    f_all, ranges = setup_for_eval_on_grid(feqs + f, [xrange, yrange], plot_points)
    xrange,yrange=[r[:2] for r in ranges]

    xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)]
                                     for y in xsrange(*ranges[1], include_endpoint=True)]
                                    for func in f_all[neqs::]],dtype=float)
    xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0))
    # Now we need to set entries to negative iff all
    # functions were negative at that point.
    neg_indices = (xy_data_arrays<0).all(axis=0)
    xy_data_array[neg_indices]=-xy_data_array[neg_indices]

    from matplotlib.colors import ListedColormap
    incol = rgbcolor(incol)
    if outcol:
        outcol = rgbcolor(outcol)
        cmap = ListedColormap([incol, outcol])
        cmap.set_over(outcol, alpha=alpha)
    else:
        outcol = rgbcolor('white')
        cmap = ListedColormap([incol, outcol])
        cmap.set_over(outcol, alpha=0)
    cmap.set_under(incol, alpha=alpha)

    g = Graphics()

    # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'.
    # Otherwise matplotlib complains.
    scale = options.get('scale', None)
    if isinstance(scale, (list, tuple)):
        scale = scale[0]
    if scale == 'semilogy' or scale == 'semilogx':
        options['aspect_ratio'] = 'automatic'

    g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax']))

    if neqs == 0:
        g.add_primitive(ContourPlot(xy_data_array, xrange,yrange,
                                dict(contours=[-1e-20, 0, 1e-20], cmap=cmap, fill=True, **options)))
    else:
        mask = numpy.asarray([[elt > 0 for elt in rows] for rows in xy_data_array], dtype=bool)
        xy_data_array = numpy.asarray([[f_all[0](x, y) for x in xsrange(*ranges[0], include_endpoint=True)]
                                        for y in xsrange(*ranges[1], include_endpoint=True)], dtype=float)
        xy_data_array[mask] = None
    if bordercol or borderstyle or borderwidth:
        cmap = [rgbcolor(bordercol)] if bordercol else ['black']
        linestyles = [borderstyle] if borderstyle else None
        linewidths = [borderwidth] if borderwidth else None
        g.add_primitive(ContourPlot(xy_data_array, xrange, yrange,
                                    dict(linestyles=linestyles, linewidths=linewidths,
                                         contours=[0], cmap=[bordercol], fill=False, **options)))

    return g
Exemplo n.º 20
0
def main():
    # White balanced
    colors = [(0,       0,       0),
        (24 ,     24   ,   112),
       ( 16 ,     78   ,   139),
      (  23  ,    116  ,   205),
      (  72 ,     118  ,   255),
      (  91 ,     172  ,   237),
      (  173 ,    215 ,    230),
      (  209 ,    237  ,   237),
      (  229 ,    239 ,    249),
      (  242 ,    255   ,  255),
      (  253 ,    245  ,   230),
      (  255 ,    228 ,    180),
      (  243 ,    164  ,   96),
      (  237 ,    118  ,   0),
      (  205 ,    102  ,   29),
      (  224  ,   49  ,    15),
      (  237 ,    0   ,    0),
      (  205 ,    0  ,     0),
      (  139 ,    0 ,      0)]
    colors = numpy.array(colors) / 255.0
    colors = ["#FFFFFF", "#7FFF00", "#00CD00", "#008B00", "#104E8B", "#1E90FF",
              "#00B2EE", "#00EEEE", "#8968CD", "#912CEE", "#8B008B", "#8B0000",
              "#CD0000", "#EE4000", "#FF7F00", "#CD8500", "#FFD700", "#EEEE00",
              "#FFFF00", "#7FFF00","#000000"]
    cmap = ListedColormap(colors[1:])
    cmap.set_over(color=colors[-1])
    cmap.set_under(color=colors[-1])
    #values = numpy.arange(0,10,0.25)
    #values = [0.01,0.05,0.1,0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0,2.5,3.0,4.0,5.0,7.5,10.0]
    values = [0.01,0.10,0.25,0.50,1.0,1.5,2.0,2.5,3.0,4.0,5.0,7.5,10.0,12.5,15.0,17.5,20.0]
    normer = BoundaryNorm(values, cmap.N, clip=False)

    ctx = {}
    
    nc = netCDF4.Dataset('/mesonet/data/iemre/2012_mw_daily.nc', 'r')
    lon = nc.variables['lon'][:]
    lat = nc.variables['lat'][:]
    ctx['llcrnrlon'] = numpy.min(lon)
    ctx['llcrnrlat'] = numpy.min(lat)
    ctx['urcrnrlon'] = numpy.max(lon)
    ctx['urcrnrlat'] = numpy.max(lat)
    setup_plot(ctx)
    
    idx = iemre.day_idx( mx.DateTime.DateTime(2012,3,1,1,5) )
    idx2 = iemre.day_idx( mx.DateTime.DateTime(2012,4,1,1,5) )
    tmpk = numpy.ma.array( numpy.sum(nc.variables['p01d'][idx:idx2,:,:],0) ) / 25.4
    
    #nx = int((ctx['map'].xmax-ctx['map'].xmin)/40000.)+1
    #ny = int((ctx['map'].ymax-ctx['map'].ymin)/40000.)+1
    #rm_tmpk,x,y = ctx['map'].transform_scalar(tmpk,nc.variables['lon'],
    #                                          nc.variables['lat'],nx,ny,
    #                                          returnxy=True,masked=True)
    #print 'Content-Type: text/plain\n'
    #print numpy.min(rm_tmpk), numpy.max(rm_tmpk)
    tmpk.mask = numpy.where(tmpk < 0.01, True, False)
    im = ctx['map'].imshow(tmpk, cmap=cmap,interpolation='nearest',norm=normer,zorder=1)
    
    cax = plt.axes([0.932,0.2,0.015,0.6])
    clr = ctx['fig'].colorbar(im, cax=cax, format='%g')
    clr.set_ticks(values)
    
    cax.text(-0.75, 0.5, 'Precipitation [inch]', transform=cax.transAxes,
    size='medium', color='k', horizontalalignment='center', 
    verticalalignment='center', rotation='vertical')
    
    ctx['plotax'].text(0.05, -0.05, 'Test test test', ha='left', va='baseline',
                       transform=ctx['plotax'].transAxes)
    
    nc.close()
    print "Content-Type: image/png\n"
    ctx['fig'].savefig(sys.stdout, format='png', edgecolor='k')
    """
Exemplo n.º 21
0
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options):
    r"""
    ``region_plot`` takes a boolean function of two variables, `f(x,y)`
    and plots the region where f is True over the specified 
    ``xrange`` and ``yrange`` as demonstrated below.

    ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)``

    INPUT:

    - ``f`` -- a boolean function of two variables

    - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple
      ``(x,xmin,xmax)``

    - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple
      ``(y,ymin,ymax)``

    - ``plot_points``  -- integer (default: 100); number of points to plot
      in each direction of the grid

    - ``incol`` -- a color (default: ``'blue'``), the color inside the region

    - ``outcol`` -- a color (default: ``'white'``), the color of the outside
      of the region

    If any of these options are specified, the border will be shown as indicated,
    otherwise it is only implicit (with color ``incol``) as the border of the 
    inside of the region.

     - ``bordercol`` -- a color (default: ``None``), the color of the border
       (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``)

    - ``borderstyle``  -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot'

    - ``borderwidth``  -- integer (default: None), the width of the border in pixels
 
    - ``legend_label`` -- the label for this item in the legend


    EXAMPLES:

    Here we plot a simple function of two variables::

        sage: x,y = var('x,y')
        sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3))
         
    Here we play with the colors::

        sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray')
        
    An even more complicated plot, with dashed borders::

        sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250)

    A disk centered at the origin::

        sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1))

    A plot with more than one condition (all conditions must be true for the statement to be true)::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2))

    Since it doesn't look very good, let's increase plot_points::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400)

    To get plots where only one condition needs to be true, use a function::

        sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2))
    
    The first quadrant of the unit circle::

        sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400)

    Here is another plot, with a huge border::

        sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50)

    If we want to keep only the region where x is positive::

        sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50)

    Here we have a cut circle::

        sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200)

    The first variable range corresponds to the horizontal axis and
    the second variable range corresponds to the vertical axis::

        sage: s,t=var('s,t')
        sage: region_plot(s>0,(t,-2,2),(s,-2,2))

    ::

        sage: region_plot(s>0,(s,-2,2),(t,-2,2))

    """

    from sage.plot.plot import Graphics
    from sage.plot.misc import setup_for_eval_on_grid
    import numpy

    if not isinstance(f, (list, tuple)):
        f = [f]

    f = [equify(g) for g in f]

    g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points)
    xrange,yrange=[r[:2] for r in ranges]

    xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)]
                                     for y in xsrange(*ranges[1], include_endpoint=True)]
                                    for func in g],dtype=float)
    xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0))
    # Now we need to set entries to negative iff all
    # functions were negative at that point.
    neg_indices = (xy_data_arrays<0).all(axis=0)
    xy_data_array[neg_indices]=-xy_data_array[neg_indices]

    from matplotlib.colors import ListedColormap
    incol = rgbcolor(incol)
    outcol = rgbcolor(outcol)
    cmap = ListedColormap([incol, outcol])
    cmap.set_over(outcol)
    cmap.set_under(incol)
    
    g = Graphics()
    g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax']))
    g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, 
                                dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options)))

    if bordercol or borderstyle or borderwidth:
        cmap = [rgbcolor(bordercol)] if bordercol else ['black']
        linestyles = [borderstyle] if borderstyle else None
        linewidths = [borderwidth] if borderwidth else None
        g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, 
                                    dict(linestyles=linestyles, linewidths=linewidths,
                                         contours=[0], cmap=[bordercol], fill=False, **options)))
    
    return g
Exemplo n.º 22
0
def masker(data, mask1=[]):

    if not isinstance(mask1, np.ndarray):
        mask1 = np.ones_like(data)

    xs = []
    ys = []
    mask = []

    def invert_mask(*args):
        ind = mask1 > 0
        mask1[ind] = 0
        mask1[~ind] = 1
        mask.set_data(mask1)

    def reset_mask(*args):
        mask1[:] = 1
        mask.set_data(mask1)

    def save_mask(*args):
        savname = savwid.value
        savname = savname.replace(".npy", "") + ".npy"
        np.save(savname, mask1.astype(bool))

    def cancel_masking(*args):
        del xs[:]
        del ys[:]
        update_plot()

    def mask_roi(*args):
        lx, ly = np.shape(mask1)
        x, y = np.meshgrid(np.arange(lx), np.arange(ly))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T
        xy = np.vstack((np.array(ys), np.array(xs))).T
        new_submask = ~path.Path(xy).contains_points(points).reshape(ly, lx).T
        np.multiply(mask1, new_submask, out=mask1)
        del xs[:]
        del ys[:]
        update_plot()

    def mask_outside(*args):
        lx, ly = np.shape(mask1)
        x, y = np.meshgrid(np.arange(lx), np.arange(ly))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T
        xy = np.vstack((np.array(ys), np.array(xs))).T
        new_submask = path.Path(xy).contains_points(points).reshape(ly, lx).T
        np.multiply(mask1, new_submask, out=mask1)
        del xs[:]
        del ys[:]
        update_plot()

    def unmask_roi(*args):
        lx, ly = np.shape(mask1)
        x, y = np.meshgrid(np.arange(lx), np.arange(ly))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T
        xy = np.vstack((np.array(ys), np.array(xs))).T
        new_submask = path.Path(xy).contains_points(points).reshape(ly, lx).T
        mask1[new_submask] = True
        del xs[:]
        del ys[:]
        update_plot()

    def above_masking(*args):
        thres = int(mvwid.value)
        mask1[data >= thres] = False
        update_plot()

    def below_masking(*args):
        thres = int(mvwid.value)
        mask1[data <= thres] = False
        update_plot()

    def onkey(event, line):
        if event.key == "c":
            cancel_masking()
        elif event.key == "m":
            mask_roi()
        elif event.key == "o":
            mask_outside()
        elif event.key == "u":
            unmask_roi()
        elif event.key == "i":
            invert_mask()
        elif event.key == "a":
            above_masking()
        elif event.key == "b":
            below_masking()

    def onclick(event, line):
        xs.append(event.xdata)
        ys.append(event.ydata)

        line.set_data(xs, ys)
        line.figure.canvas.draw_idle()

    def update_plot(*args):
        line.set_data(xs, ys)
        mask.set_data(mask1.astype(int))

    mvwid = widgets.Text(value="0",
                         description="mask value:",
                         placeholder="type herer",
                         disabled=False)
    above_button = widgets.Button(
        description="mask >= (a)",
        disabled=False,
        tooltip="all values set to default",
    )
    above_button.on_click(above_masking)
    below_button = widgets.Button(
        description="mask <= (b)",
        disabled=False,
        tooltip="all values set to default",
    )
    below_button.on_click(below_masking)
    row_thres = widgets.HBox([mvwid, above_button, below_button])

    cancel_button = widgets.Button(
        description="cancel (c)",
        disabled=False,
        tooltip="cancel roi",
    )
    cancel_button.on_click(cancel_masking)
    reset_button = widgets.Button(
        description="reset",
        disabled=False,
        tooltip="all values set to default",
    )
    reset_button.on_click(reset_mask)

    row3 = widgets.HBox([cancel_button, reset_button])

    mask_button = widgets.Button(
        description="mask (m)",
        disabled=False,
        tooltip="mask roi",
        icon="",
    )
    mask_button.on_click(mask_roi)
    unmask_button = widgets.Button(
        description="unmask (u)",
        disabled=False,
        tooltip="unmask roi",
    )
    unmask_button.on_click(unmask_roi)
    outside_button = widgets.Button(
        description="mask outside (o)",
        disabled=False,
        tooltip="mask everything outside the roi",
    )
    outside_button.on_click(mask_outside)
    invert_button = widgets.Button(
        description="invert (i)",
        disabled=False,
        tooltip="invert the complete mask",
        icon="",
    )
    invert_button.on_click(invert_mask)

    row2 = widgets.HBox(
        [mask_button, unmask_button, outside_button, invert_button])

    savwid = widgets.Text(
        value="example_mask.npy",
        placeholder="type here",
        description="Filename:",
        disabled=False,
    )
    cdir_button = widgets.Button(
        description="change directory",
        disabled=False,
        tooltip="change saving directory",
    )
    save_button = widgets.Button(
        description="save mask",
        disabled=False,
        tooltip="save mask to npy file",
    )
    save_button.on_click(save_mask)
    row_save = widgets.HBox([savwid, cdir_button, save_button])

    out = widgets.Output()
    display(out)
    with out:

        display(widgets.VBox([row2, row3, row_thres, row_save]))

        fig, ax = plt.subplots(figsize=(8, 8))
        ax.set_position([0.06, 0.05, 0.94, 0.94])

        cmap = mpl.colors.ListedColormap(["orange", "white"])

        # Get the colormap colors
        my_cmap = cmap(np.arange(cmap.N))

        # Set alpha
        my_cmap[:, -1] = 0.7

        # Create new colormap
        cmap = ListedColormap(my_cmap)
        cmap.set_over("orange", alpha=0)

        bounds = [0, 0.5, 1]
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        ax.imshow(
            data,
            interpolation="nearest",
            norm=mpl.colors.LogNorm(),
            aspect="auto",
        )
        mask = plt.imshow(
            mask1.astype(int),
            interpolation="nearest",
            norm=norm,
            cmap=cmap,
            aspect="auto",
        )
        plt.axis("equal")
        (line, ) = ax.plot([], [], ".-k")
        cid_m = fig.canvas.mpl_connect("button_press_event",
                                       lambda event: onclick(event, line))
        cid_k = fig.canvas.mpl_connect("key_press_event",
                                       lambda event: onkey(event, line))
        plt.show()
Exemplo n.º 23
0
    numPixelIntp = np.concatenate([numPixelIntp[:, :, 180:], 
                                   numPixelIntp[:, :, :180]], 2)

    # define the equal-angle grid
    lons, lats = np.meshgrid(np.linspace(-179.5, 179.5, 360), 
                             np.linspace(-89.5, 89.5, 180))
    lonedges, latedges = np.meshgrid(np.linspace(-180, 180, 361), 
                                     np.linspace(-90, 90, 181))

    # set up the plot
    m = Basemap(projection = 'moll', lon_0 = 0, resolution = 'c')
    bounds = np.arange(t0 / 2, t1 / 2 + 0.6, 0.5)
    cmap1 = ListedColormap(('#bbd6e8', '#ffd8b6', '#bfe2bf', 
                            '#f2bebe', '#ded1eb', '#dcccc9'))
    cmap1.set_under('w')
    cmap1.set_over('w')
    cols = ('C0', 'C1', 'C2', 'C3', 'C4', 'C5')
    cmap2 = ListedColormap(cols)

    plt.figure(figsize = (scol, 0.7 * scol))
    mp = m.pcolormesh(lonedges, latedges, UTC, 
                      norm = BoundaryNorm(bounds, cmap1.N), cmap = cmap1, 
                      latlon = True, rasterized = True)
    for hhr, col in zip(range(t1 - t0 + 1), cols):
        m.contour(lons, lats, numPixelIntp[hhr] > 0, 1, colors = col, 
                  linewidths = 1, latlon = True)
    m.drawcoastlines(linewidth = 0.5)
    m.drawparallels((-60, 60))
    cb = ColorbarBase(plt.axes([0.125, 0.1, 0.775, 0.025]), cmap = cmap2,
                      orientation = 'horizontal',
                      norm = BoundaryNorm(bounds, cmap2.N))
Exemplo n.º 24
0
def utci_heatmap(df, y_move=-0.22, savepath=None, close=True):
    series = df.UniversalThermalClimateIndex.to_frame()
    series = series.rolling(2).mean()
    colors = [
        '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899',
        '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899',
        '#1A5899', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9',
        '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9',
        '#347FB9', '#347FB9', '#347FB9', '#82BBD9', '#82BBD9', '#82BBD9',
        '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9',
        '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#BFDCEB', '#BFDCEB',
        '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB',
        '#BFDCEB', '#BFDCEB', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
        '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
        '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
        '#FFFFFF', '#F7C1AA', '#F7C1AA', '#F7C1AA', '#F7C1AA', '#F7C1AA',
        '#F7C1AA', '#E3806B', '#E3806B', '#E3806B', '#E3806B', '#E3806B',
        '#E3806B', '#C84648', '#C84648', '#C84648', '#C84648', '#C84648',
        '#C84648', '#C84648', '#C84648'
    ]
    cmap = ListedColormap(colors)
    cmap.set_under('#053061')
    cmap.set_over('#B2182B')
    bounds = np.arange(-41, 48, 1)
    norm = BoundaryNorm(bounds, cmap.N)
    fig, ax = plt.subplots(1, 1, figsize=(15, 5))
    heatmap = ax.imshow(pd.pivot_table(
        series,
        index=series.index.time,
        columns=series.index.date,
        values="UniversalThermalClimateIndex").values[::-1],
                        extent=[
                            dates.date2num(series.index.min()),
                            dates.date2num(series.index.max()), 726449, 726450
                        ],
                        aspect='auto',
                        cmap=cmap,
                        interpolation='none',
                        vmin=-40,
                        vmax=46)
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(dates.DateFormatter('%b'))
    ax.yaxis_date()
    ax.yaxis.set_major_formatter(dates.DateFormatter('%H:%M'))
    ax.invert_yaxis()
    ax.tick_params(labelleft=True, labelright=True, labelbottom=True)
    plt.setp(ax.get_xticklabels(), ha='left', color='#555555')
    plt.setp(ax.get_yticklabels(), color='#555555')
    [
        ax.spines[spine].set_visible(False)
        for spine in ['top', 'bottom', 'left', 'right']
    ]
    ax.grid(b=True, which='major', color='white', linestyle='--', alpha=0.9)
    cb = fig.colorbar(heatmap,
                      cmap=cmap,
                      norm=norm,
                      boundaries=bounds,
                      orientation='horizontal',
                      drawedges=False,
                      fraction=0.05,
                      aspect=100,
                      pad=0.1,
                      extend='both',
                      ticks=[-40, -27, -13, 0, 9, 26, 32, 38, 46])
    plt.setp(plt.getp(cb.ax.axes, 'xticklabels'), color='#555555')
    cb.outline.set_visible(False)
    ax.set_title("UTCI approximation (°C)\n{0:} - {1:} - {2:}".format(
        df.City[0], df.Country[0], df.StationID[0]),
                 color='#555555',
                 y=1.03)
    ax.text(0,
            y_move,
            'Extreme\ncold stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(-27 + (-40 - -27) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Very strong\ncold stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(-13 + (-27 - -13) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Strong\ncold stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(0 + (-13 - 0) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Moderate\ncold stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(0 + (9 - 0) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Slight\ncold stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(9 + (26 - 9) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'No thermal stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(26 + (32 - 26) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Moderate\nheat stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(32 + (38 - 32) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Strong\nheat stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(np.interp(38 + (46 - 38) / 2, [-44.319, 50.319], [0, 1]),
            y_move,
            'Very strong\nheat stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    ax.text(1,
            y_move,
            'Extreme\nheat stress',
            ha='center',
            va='center',
            transform=ax.transAxes,
            color='#555555',
            fontsize='small')
    plt.tight_layout()

    # Save figure
    if savepath != None:
        print("Saving to {}".format(savepath))
        fig.savefig(savepath, bbox_inches="tight", dpi=300, transparent=False)
    if close:
        plt.close()
print('avg acc:', pat_avg_acc)
print('dice:', pat_dice)
print()

# -----------------------------------------------------------
# VISUALIZATION OF PICKED SLICES
# -----------------------------------------------------------
print('Plotting...')
fig = plt.figure(1, figsize=(9, 9.5))

slices = [37, 65, 77, 105]
num_columns = 5
cmap1 = 'gray'
cmap2 = 'gist_heat'
cmap3 = ListedColormap(['black', 'cyan', 'red', 'white'])
cmap3.set_over('1')
cmap3.set_under('0')
fontsize = 12

for i, sl in enumerate(slices):
    plt.subplot(len(slices), num_columns, (i * num_columns) + 1)
    plt.title('MRA scan', fontsize=fontsize) if i == 0 else 0
    plt.ylabel('Slice ' + str(sl),
               rotation='vertical',
               labelpad=4,
               fontsize=fontsize)
    plt.yticks([])
    plt.xticks([])
    plt.imshow(img_mat.T[sl], cmap=cmap1)

    plt.subplot(len(slices), num_columns, (i * num_columns) + 2)
Exemplo n.º 26
0
"""This file contains GUI related variables."""

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

# Colormap for mask overlays
# palette = plt.cm.Reds
palette = ListedColormap([[0, 0, 0, 0], [1, 0, 1, 1]])  # white and magenta improve the visibility
palette.set_over('r', 1.0)
palette.set_under('w', 0)
palette.set_bad('m', 1.0)

# Slider colors
axcolor = '0.875'
hovcolor = '0.975'
Exemplo n.º 27
0
def masker(data, mask1=[]):

    if not isinstance(mask1, np.ndarray):
        mask1 = np.ones_like(data)

    xs = []
    ys = []
    mask = []

    def invert_mask(*args):
        ind = mask1 > 0
        mask1[ind] = 0
        mask1[~ind] = 1
        mask.set_data(mask1)

    def reset_mask(*args):
        mask1[:] = 1
        mask.set_data(mask1)

    def save_mask(*args):
        savname = savwid.value
        savname = savname.replace('.npy', "") + '.npy'
        np.save(savname, mask1.astype(bool))

    def cancel_masking(*args):
        del xs[:]
        del ys[:]
        line.set_data(xs, ys)
        line.figure.canvas.draw_idle()

    def mask_roi(*args):
        lx, ly = np.shape(mask1)
        x, y = np.meshgrid(np.arange(lx), np.arange(ly))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T
        xy = np.vstack((np.array(ys), np.array(xs))).T
        new_submask = ~path.Path(xy).contains_points(points).reshape(ly, lx).T
        np.multiply(mask1, new_submask, out=mask1)
        del xs[:]
        del ys[:]
        mask.set_data(mask1.astype(int))

    def mask_outside(*args):
        lx, ly = np.shape(mask1)
        x, y = np.meshgrid(np.arange(lx), np.arange(ly))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T
        xy = np.vstack((np.array(ys), np.array(xs))).T
        new_submask = path.Path(xy).contains_points(points).reshape(ly, lx).T
        np.multiply(mask1, new_submask, out=mask1)
        del xs[:]
        del ys[:]
        mask.set_data(mask1.astype(int))

    def unmask_roi(*args):
        lx, ly = np.shape(mask1)
        x, y = np.meshgrid(np.arange(lx), np.arange(ly))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x, y)).T
        xy = np.vstack((np.array(ys), np.array(xs))).T
        new_submask = path.Path(xy).contains_points(points).reshape(ly, lx).T
        mask1[new_submask] = True
        del xs[:]
        del ys[:]
        mask.set_data(mask1.astype(int))

    def onclick(event, line):
        xs.append(event.xdata)
        ys.append(event.ydata)

        line.set_data(xs, ys)
        line.figure.canvas.draw_idle()

    def onkey(event, line):
        if event.key == 'c':
            cancel_masking()
        elif event.key == 'm':
            mask_roi()
        elif event.key == 'o':
            mask_outside()
        elif event.key == 'u':
            unmask_roi()
        elif event.key == 'i':
            invert_mask()

    savwid = widgets.Text(value='example_mask.npy',
                          placeholder='type here',
                          description='Filename:',
                          disabled=False)
    mvwid = widgets.Text(value='0',
                         description='mask value:',
                         placeholder='type herer',
                         disabled=False)
    row1 = widgets.HBox([savwid, mvwid])

    invert_button = widgets.Button(
        description='invert (i)',
        disabled=False,
        tooltip='invert the complete mask',
        icon='',
    )
    invert_button.on_click(invert_mask)
    reset_button = widgets.Button(
        description='reset',
        disabled=False,
        tooltip='all vales set to default',
    )
    reset_button.on_click(reset_mask)
    save_button = widgets.Button(
        description='save mask',
        disabled=False,
        tooltip='save mask to npy file',
    )
    save_button.on_click(save_mask)
    row3 = widgets.HBox([invert_button, reset_button, save_button])

    mask_button = widgets.Button(
        description='mask (m)',
        disabled=False,
        tooltip='mask roi',
        icon='',
    )
    mask_button.on_click(mask_roi)
    unmask_button = widgets.Button(
        description='unmask (u)',
        disabled=False,
        tooltip='unmask roi',
    )
    unmask_button.on_click(unmask_roi)
    outside_button = widgets.Button(
        description='mask outside (o)',
        disabled=False,
        tooltip='mask everything outside the roi',
    )
    outside_button.on_click(mask_outside)
    cancel_button = widgets.Button(
        description='cancel (c)',
        disabled=False,
        tooltip='cancel roi',
    )
    cancel_button.on_click(cancel_masking)
    row2 = widgets.HBox(
        [mask_button, unmask_button, outside_button, cancel_button])

    out = widgets.Output()
    display(out)
    with out:

        display(widgets.VBox([row1, row2, row3]))

        fig = plt.figure(figsize=(8, 8))
        ax = plt.axes(position=[.06, .05, .94, .94])
        plt.ion()

        cmap = mpl.colors.ListedColormap(['orange', 'white'])

        # Get the colormap colors
        my_cmap = cmap(np.arange(cmap.N))

        # Set alpha
        my_cmap[:, -1] = 0.7

        # Create new colormap
        cmap = ListedColormap(my_cmap)
        cmap.set_over('orange', alpha=0)

        bounds = [0, .5, 1]
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        ax.imshow(data,
                  interpolation='none',
                  norm=mpl.colors.LogNorm(),
                  aspect='auto')
        mask = plt.imshow(mask1.astype(int),
                          interpolation='none',
                          norm=norm,
                          cmap=cmap,
                          aspect='auto')
        line, = ax.plot([], [], '.-k')
        cid_m = fig.canvas.mpl_connect('button_press_event',
                                       lambda event: onclick(event, line))
        cid_k = fig.canvas.mpl_connect('key_press_event',
                                       lambda event: onkey(event, line))
        fig.canvas.draw()
Exemplo n.º 28
0
      (  255 ,    228 ,    180),
      (  243 ,    164  ,   96),
      (  237 ,    118  ,   0),
      (  205 ,    102  ,   29),
      (  224  ,   49  ,    15),
      (  237 ,    0   ,    0),
      (  205 ,    0  ,     0),
      (  139 ,    0 ,      0)]
colors = numpy.array(colors) / 255.0

#colors = ["#FFFFFF", "#7FFF00", "#00CD00", "#008B00", "#104E8B", "#1E90FF",
#             "#00B2EE", "#00EEEE", "#8968CD", "#912CEE", "#8B008B", "#8B0000",
#             "#CD0000", "#EE4000", "#FF7F00", "#CD8500", "#FFD700", "#EEEE00",
#             "#FFFF00", "#7FFF00","#000000"]
cmap = ListedColormap(colors[:])
cmap.set_over(color=colors[-1])
cmap.set_under(color=colors[0])
normer = BoundaryNorm(values, cmap.N, clip=False)


#data_proj,x,y = map.transform_scalar(data,lons,lats,nx,ny,returnxy=True)
cax = plt.axes([0.902,0.2,0.03,0.6])
res = map.imshow(data, interpolation='nearest', cmap=cmap,
      norm=normer, ax=ax)
clr = plt.colorbar(res, cax=cax, format='%g')
clr.set_ticks(values)
map.drawcoastlines(ax=ax)
map.drawstates(ax=ax)
map.drawcountries(ax=ax)

logo = Image.open('NARCCAP.png')
Exemplo n.º 29
0
def colour_map(colours,
               match_colour=None,
               match_value=None,
               dmin=None,
               dmax=None,
               data=None,
               cmap_len=256,
               extend='neither'):
    """
    Return a matplotlib colour map from a list of colours. A single colour 
    within the list can be assigned a value by providing the data limits that 
    the colour map will be used on. Note, if using this functionality, 
    match_colour, match_value and data limits (or all the data) must be 
    provided.
    
    Args:
    
    * colours: list
        A list of matplotlib accepted colours. These include names (see 
        http://www.w3schools.com/html/html_colornames.asp), html hex colour 
        codes and RGB arrays.
    
    Kwargs:
    
    * match_colour: string or RBG array
        Specify one of the colours in the colour list (but not the first or 
        last) to be matched against a given value (see below).
    
    * match_value: float
        Specify a value to which a given colour is to be matched.
    
    * dmin: float
        Data minimum.
    
    * dmax: 
        Data maximum
        
    * data: array like
        Alternative to providing the limits. Limits are calculated using the 
        data within the function.
    
    * cmap_len: integer
        Total number of colours in the colour map.
    
    * extend: 'neither' or 'both'
        If 'both', the first and last colours are set to under and over data
        range colours.
    
    Returns:
        matplotlib.colors.Colormap
    
    """
    cmap = LinearSegmentedColormap.from_list('cmap', colours, N=cmap_len)
    if match_colour is not None:
        assert match_value is not None, 'A value must be given with which to '\
        'match the colour.'
        colours = [colour.lower() for colour in colours]
        match_colour = match_colour.lower()
        assert match_colour in colours, 'The colour to match, %s, is not in'\
        ' the given colours list, %s.' % (match_colour, colours)
        if dmin is None or dmax is None:
            assert data is not None, 'To scale the colour map, data or data '\
            'minimum and maximum must be provided.'
            dmin = numpy.min(data)
            dmax = numpy.max(data)
        else:
            assert dmin is not None and dmax is not None, 'Both dmin and dmax'\
            ' must be provided.'
            assert dmin < dmax, 'dmin must be smaller than dmax.'

        assert dmin <= match_value <= dmax, 'match_value, %s, value must fall'\
        ' within the data range, %s & %s.' % (match_value, dmin, dmax)

        colour_position = float(colours.index(match_colour)) / \
                          float(len(colours) - 1)
        if colour_position in [0., 1]:
            raise UserWarning('The colour to match the value cannot be a '\
                              'colour on the limits of the colour map.')
        value_position = float(match_value - dmin) / \
                               float(dmax - dmin)

        if value_position > colour_position:
            # Cut off the top end of the colour map using equation...
            x = (colour_position * cmap.N) / value_position
            # Take colours from 0 to x (+1 for range to reach x value)
            colour_RGBs = cmap(range(int(round(x + 1))))
            cmap = ListedColormap(colour_RGBs)
        elif value_position < colour_position:
            # Cut off the bottom end of the colour map using equation...
            x = ((colour_position - value_position) * cmap.N) / \
                 (1. - value_position)
            # Take colours from x to end colour index (+1 for range to reach x
            # value)
            colour_RGBs = cmap(range(int(round(x)), (cmap.N + 1)))
            cmap = ListedColormap(colour_RGBs)
    else:
        assert match_value is None, 'A value has been specified without a '\
        'colour to match it with.'
    if extend == 'both':
        over_colour = cmap(cmap.N)
        under_colour = cmap(0)
        colour_RGBs = cmap(range(1, cmap.N - 1))
        cmap = ListedColormap(colour_RGBs)
        cmap.set_over(over_colour)
        cmap.set_under(under_colour)

    return cmap
Exemplo n.º 30
0
def create_mp4_prediction(top_video_fullpath,
                          top_pose_fullpath,
                          pred_file_fullpath,
                          video_savename,
                          queue_for_number_processed):
    try:
        #top video and pose info
        video_name = os.path.basename(top_video_fullpath)
        with open(top_pose_fullpath, 'r') as fp:
            frames_pose = json.load(fp)
        num_pt = len(frames_pose['scores'][0][0])
        keypoints = frames_pose['keypoints']
        scores = frames_pose['scores']

        ext = top_video_fullpath[-3:]

        if ext == 'seq':
            srTop = seqIo_reader(top_video_fullpath)
            IM_TOP_W = srTop.header['width']
            IM_TOP_H = srTop.header['height']
            fps = srTop.header['fps']
        elif any(x not in ext for x in ['avi', 'mpg']):
            vc = cv2.VideoCapture(top_video_fullpath)
            if vc.isOpened():
                rval = True
            else:
                rval = False
                print('video not readable')
            fps = vc.get(cv2.CAP_PROP_FPS)
            if np.isnan(fps): fps = 30.
            IM_TOP_W = int(vc.get(cv2.CAP_PROP_FRAME_HEIGHT))
            IM_TOP_H = int(vc.get(cv2.CAP_PROP_FRAME_WIDTH))
        num_frames = len(keypoints)

        actions_pred = parse_ann_dual(pred_file_fullpath)
        ####################################################################
        plt.ioff()
        fig = plt.figure(figsize=(float(IM_TOP_W-150) / 100.0, float(IM_TOP_H + 100) / 100.0), dpi=100, frameon=False)
        fig.patch.set_visible(False)
        gs1 = gridspec.GridSpec(9, 12)
        gs1.update(left=0, right=1, hspace=0.5,bottom=0.05, top=1,wspace=0.)
        gs1.tight_layout(fig)
        ax = fig.add_subplot(gs1[:-2, :])
        # ax = plt.subplot2grid((5, 5), (0, 0), colspan=5, rowspan=4)
        # ax.add_axes([0.0, 0.0, 1.0, 1.0])
        ax.set_xlim([0, IM_TOP_W])
        ax.set_ylim([IM_TOP_H, 0])
        ax.set_axis_off()
        ax.axes.get_yaxis().set_visible(False)
        ax.axes.get_xaxis().set_visible(False)
        im = ax.imshow(np.ones((IM_TOP_H, IM_TOP_W)), cmap='gray', interpolation='nearest')
        im.set_clim([0, 1])

        # prediction behaviors
        # ax2 = plt.subplot2grid((5, 5), (4, 1), colspan=3, rowspan=1)
        ax2  = fig.add_subplot(gs1[-2, 1:-2])
        ax2.set_xlim([0, 300])
        ax2.set_ylim([20, 0])
        # ax2.set_axis_off()
        ax2.axes.get_yaxis().set_visible(False)
        ax2.axes.get_xaxis().set_visible(False)

        # prediction interactions
        ax3  = fig.add_subplot(gs1[-1, 1:-2])
        ax3.set_xlim([0, 300])
        ax3.set_ylim([20, 0])
        # x2.set_axis_off()
        ax3.axes.get_yaxis().set_visible(False)
        ax3.axes.get_xaxis().set_visible(False)

        num_pt = len(keypoints[0][0][0])

        # mouse 1 and 2 body part dots
        pts = []
        colors = ['y' for i in range(num_pt)] + ['b' for i in range(num_pt)]
        for i in range(num_pt * 2):
            pt = mpatches.Ellipse((0, 0), 2, 2, 0, color='none', ec=colors[i], fc =colors[i] )
            ax.add_patch(pt)
            pts.append(pt)

        #mouse 1 lines
        l11 =  Line2D([100,200], [100,200], linewidth=2, color = 'r');  ax.add_line(l11)
        l12 =  Line2D([100,200], [100,200], linewidth=2, color = '#ffa07a');  ax.add_line(l12)
        l13 =  Line2D([100,200], [100,200], linewidth=2, color = 'yellow');  ax.add_line(l13)
        l14 =  Line2D([100,200], [100,200], linewidth=2, color = 'orange');  ax.add_line(l14)
        l15 =  Line2D([100,200], [100,200], linewidth=2, color = 'orange');  ax.add_line(l15)
        l16 =  Line2D([100,200], [100,200], linewidth=2, color = '#ff1493');  ax.add_line(l16)
        l17 =  Line2D([100,200], [100,200], linewidth=2, color = '#ff1493');  ax.add_line(l17)

        #mouse 3 lines
        l21 =  Line2D([100,200], [100,200], linewidth=2, color = '#000080');  ax.add_line(l21)
        l22 =  Line2D([100,200], [100,200], linewidth=2, color = '#6495ed');  ax.add_line(l22)
        l23 =  Line2D([100,200], [100,200], linewidth=2, color = 'b');  ax.add_line(l23)
        l24 =  Line2D([100,200], [100,200], linewidth=2, color = 'chartreuse');  ax.add_line(l24)
        l25 =  Line2D([100,200], [100,200], linewidth=2, color = 'chartreuse');  ax.add_line(l25)
        l26 =  Line2D([100,200], [100,200], linewidth=2, color = 'cyan');  ax.add_line(l26)
        l27 =  Line2D([100,200], [100,200], linewidth=2, color = 'cyan');  ax.add_line(l27)

        # add predicted labels to subplot
        label2id = {'other': 0,
                'cable_fix': 0,
                'intruder_introduction': 0,
                'corner': 0,
                'ignore': 0,
                'groom': 0,
                'groom_genital': 0,
                'grooming': 0,
                'tailrattle': 0,
                'tail_rattle': 0,
                'tailrattling': 0,
                'intruder_attacks': 0,
                'approach': 0,

                'closeinvestigate': 1,
                'closeinvestigation': 1,
                'investigation': 1,
                'sniff_genitals': 1,
                'sniff-genital': 1,
                'sniff-face': 1,
                'sniff-body': 1,
                'sniffurogenital': 1,
                'sniffgenitals': 1,
                'agg_investigation': 1,
                'sniff_face': 1,
                'anogen-investigation': 1,
                'head-investigation': 1,
                'sniff_body': 1,
                'body-investigation': 1,
                'socialgrooming': 1,

                'mount': 2,
                'aggressivemount': 2,
                'mount_attempt': 2,
                'intromission': 2,

                'attack': 3,

                'interaction':4

                    }

        if 'interaction' in actions_pred['behs_frame']:
            pred_lab = actions_pred['behs_frame2']
            pred_lab_int = actions_pred['behs_frame']
        else:
            pred_lab = actions_pred['behs_frame']
            pred_lab_int = actions_pred['behs_frame2']

        labels_pred=[]
        for i in pred_lab:
            labels_pred.append(label2id[i]) if i in label2id else labels_pred.append(0)
        labels_pred.insert(0,0)

        labels_pred_int=[]
        for i in pred_lab_int:
            labels_pred_int.append(label2id[i]) if i in label2id else labels_pred_int.append(0)
        labels_pred_int.insert(0,0)

        # define the colormap
        # cmap = cm.jet
        # extract all colors from the .jet map
        # cmaplist = [cmap(i) for i in range(cmap.N)]
        # force the first color entry to be grey
        # cmaplist[-1] = (.5,.5,.5,1.0)
        # create the new map
        # cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

        # cmap = cm.ScalarMappable(col.Normalize(0, len(class_names)), cm.jet)
        # cmap = cmap.to_rgba(range(len(class_names)))
        # cmap = mpl.colors.ListedColormap(cmap)

        class_names = ['other', 'closeinvestigate', 'mount', 'attack','interaction']
        colors=['white','blue','green','red','grey']
        cmap = ListedColormap(colors)
        cmap.set_over('0.25')
        cmap.set_under('0.75')
        # define the bins and normalize
        bounds = np.linspace(0,5,6)
        norm = col.BoundaryNorm(bounds, cmap.N)

        # behs pred
        pd_mat = np.tile(np.array(labels_pred[:300]),(20,1))
        im2 = ax2.imshow(pd_mat,cmap=cmap,norm=norm)
        pd_ind = mpatches.Rectangle((0,0), 1.5, 20, angle=0.0, color='none', ec='black',linewidth=1)
        ax2.add_patch(pd_ind)
        pd_text = ax2.text(148, -2, "0")
        pd_tag = ax2.text(-30,12, "BEHS")

        # interaction pred
        pd_mat_int = np.tile(np.array(labels_pred_int[:300]),(20,1))
        im3 = ax3.imshow(pd_mat_int,cmap=cmap,norm=norm)
        # gt_line = Line2D([IM_TOP_W/2,IM_TOP_W/2],[0,50],color='r', linewidth=3); ax2.add_line(gt_line)
        pd_ind_int = mpatches.Rectangle((0,0), 1.5, 20, angle=0.0, color='none', ec='black',linewidth=1)
        ax3.add_patch(pd_ind_int)
        pd_tag_int = ax3.text(-30, 12, "INTER")

        # colorbar
        ticks = class_names
        # create a second axes for the colorbar
        ax4= fig.add_axes([0.85, 0.03, 0.015, 0.2])
        # ax3.set_axis_off()
        cb = cbar.ColorbarBase(ax4, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds+.5, boundaries=bounds)
        cb.ax.tick_params(labelsize=8)
        cb.ax.set_yticklabels(ticks)

        bar = progressbar.ProgressBar(widgets=
                                      [progressbar.FormatLabel('frame %(value)d'), '/' , progressbar.FormatLabel('%(max)d  '), progressbar.Percentage(), ' -- ', ' [', progressbar.Timer(), '] ',
                                       progressbar.Bar(), ' (', progressbar.ETA(), ') '], maxval=len(keypoints))
        bar.start()
        queue_for_number_processed.put([0,num_frames-1])

        def animate(f):
            queue_for_number_processed.put([f,0])
            # get current frame's mouse data
            x1 = np.array(keypoints[f][0][0])
            y1 = np.array(keypoints[f][0][1])
            x2 = np.array(keypoints[f][1][0])
            y2 = np.array(keypoints[f][1][1])
            s1 = np.array(scores[f][0])
            s2 = np.array(scores[f][1])

            if ext == 'seq':
                frame = srTop.getFrame(f)[0]
            else:
                vc.set(cv2.CAP_PROP_POS_FRAMES, f)
                _, frame = vc.read()
                frame = frame.astype(np.float32)
            im.set_data(frame / 256.)

            for i in range(7):
                ms1 = min(np.sqrt(s1[i]) * 15.0, 15.0)
                pts[i].center = (x1[i], y1[i])
                pts[i].width = ms1
                pts[i].height = ms1
                ms2 = min(np.sqrt(s2[i]) * 15.0, 15.0)
                pts[i + 7].center = (x2[i], y2[i])
                pts[i + 7].width = ms2
                pts[i + 7].height = ms2

            l11.set_data([x1[1], x1[2]], [y1[1], y1[2]]);    l11.set_linewidth(1.5 if np.min(s1[1:3]) < 0.5 else 3.5)
            l12.set_data([x1[0], x1[1]], [y1[0], y1[1]]);    l12.set_linewidth(1.5 if np.min([s1[0],s1[2]]) < 0.5 else 3.5)
            l13.set_data([x1[0], x1[2]], [y1[0], y1[2]]);    l13.set_linewidth(1.5 if np.min([s1[3],s1[4]]) < 0.5 else 3.5)
            l14.set_data([x1[3], x1[4]], [y1[3], y1[4]]);    l14.set_linewidth(1.5 if np.min([s1[4],s1[6]]) < 0.5 else 3.5)
            l15.set_data([x1[4], x1[6]], [y1[4], y1[6]]);    l15.set_linewidth(1.5 if np.min([s1[0],s1[2]]) < 0.5 else 3.5)
            l16.set_data([x1[3], x1[5]], [y1[3], y1[5]]);    l16.set_linewidth(1.5 if np.min([s1[3],s1[5]]) < 0.5 else 3.5)
            l17.set_data([x1[5], x1[6]], [y1[5], y1[6]]);    l17.set_linewidth(1.5 if np.min([s1[5],s1[6]]) < 0.5 else 3.5)

            l21.set_data([x2[1], x2[2]], [y2[1], y2[2]]);    l21.set_linewidth(1.5 if np.min(s2[1:3]) < 0.5 else 3.5)
            l22.set_data([x2[0], x2[1]], [y2[0], y2[1]]);    l22.set_linewidth(1.5 if np.min([s2[0],s2[2]]) < 0.5 else 3.5)
            l23.set_data([x2[0], x2[2]], [y2[0], y2[2]]);    l23.set_linewidth(1.5 if np.min([s2[3],s2[4]]) < 0.5 else 3.5)
            l24.set_data([x2[3], x2[4]], [y2[3], y2[4]]);    l24.set_linewidth(1.5 if np.min([s2[4],s2[6]]) < 0.5 else 3.5)
            l25.set_data([x2[4], x2[6]], [y2[4], y2[6]]);    l25.set_linewidth(1.5 if np.min([s2[0],s2[2]]) < 0.5 else 3.5)
            l26.set_data([x2[3], x2[5]], [y2[3], y2[5]]);    l26.set_linewidth(1.5 if np.min([s2[3],s2[5]]) < 0.5 else 3.5)
            l27.set_data([x2[5], x2[6]], [y2[5], y2[6]]);    l27.set_linewidth(1.5 if np.min([s2[5],s2[6]]) < 0.5 else 3.5)

            pd_text.set_text(str(f))

            if f >= 300:
                pd_mat = np.tile(np.array(labels_pred[f-150:f+151]), (20, 1))
                im2.set_data(pd_mat)
                pd_ind.set_xy((150,0))
                pd_mat_int = np.tile(np.array(labels_pred_int[f - 150:f + 151]), (20, 1))
                im3.set_data(pd_mat_int)
                pd_ind_int.set_xy((150, 0))
            else:
                pd_ind.set_xy((f,0))
                pd_ind_int.set_xy((f,0))
            bar.update(f)
            return
        # print("animating")
        ani = FuncAnimation(fig, animate, repeat=False, blit=False, frames= num_frames)

        mywriter = FFMpegWriter(fps=fps)
        ani.save(video_savename, writer=mywriter, dpi=200)
        queue_for_number_processed.put([])
        bar.finish()
        plt.close()
        if ext == 'seq':        srTop.close()
        else: vc.release()
        return
    except Exception as e:
        print(e)
        raise(e)
Exemplo n.º 31
0
def plotmap(arr, lon, lat, fig_title, pal='anom'):

    fig_map = plt.figure(figsize=(10, 7))

    proj = cart.crs.PlateCarree(central_longitude=0)  # -156

    ax = plt.axes(projection=proj)

    if pal == 'anom':

        pal = [
            '#000044', '#0033FF', '#007FFF', '#0099FF', '#00B2FF', '#00CCFF',
            '#FFFFFF', '#FFCC00', '#FF9900', '#FF7F00', '#FF3300', '#A50000',
            '#B48C82'
        ]
        clevs = [-3., -2.5, -2., -1.5, -1., -0.5, 0.5, 1., 1.5, 2., 2.5, 3.]
        orient = 'horizontal'
        shrink = 1.
        aspect = 35

    elif pal == 'diff':

        pal = ('#0033FF', '#0099FF', '#FFFFFF', '#FFCC00', '#FF3300')
        clevs = [-1., -0.05, 0.05, 1.]
        orient = 'horizontal'
        shrink = 0.45
        aspect = 9

    else:

        pal = [
            '#D204A9', '#B605C1', '#9406DF', '#7907F7', '#5A45F9', '#368FFB',
            '#18CDFD', '#00F8E1', '#00E696', '#00D13C', '#0CC600', '#4CD500',
            '#99E700', '#D8F600', '#FFE900', '#FFB400', '#FF7400', '#FF3F00'
        ]
        clevs = list(range(-2, 31, 2))
        orient = 'horizontal'
        shrink = 1.
        aspect = 35

    ccols = ListedColormap(pal[1:-1])
    ccols.set_under(pal[0])
    ccols.set_over(pal[-1])

    norm = BoundaryNorm(clevs, ncolors=ccols.N, clip=False)

    img = ax.contourf(lon,
                      lat,
                      arr,
                      cmap=ccols,
                      levels=clevs,
                      extend='both',
                      norm=norm,
                      transform=proj)

    ax.gridlines(crs=proj,
                 linewidth=1.5,
                 color='black',
                 alpha=0.5,
                 linestyle='--',
                 draw_labels=False)

    parallels = list(range(-180, 181, 40))
    meridians = list(range(-90, 91, 20))

    ax.set_xticks(parallels, crs=proj)
    ax.set_yticks(meridians, crs=proj)
    ax.set_xticklabels(parallels, rotation=0, fontsize=10, fontweight='bold')
    ax.set_yticklabels(meridians, rotation=0, fontsize=10, fontweight='bold')

    ax.add_feature(
        cart.feature.LAND,
        zorder=50,
        edgecolor='k',  #808080
        facecolor='k')

    ax.set_extent([-180, 180, -80, 80], proj)

    bar = fig_map.colorbar(img,
                           pad=0.08,
                           spacing='uniform',
                           orientation=orient,
                           extend='both',
                           ax=ax,
                           extendfrac='auto',
                           ticks=clevs,
                           shrink=shrink,
                           aspect=aspect)

    bar.ax.tick_params(labelsize=11)

    # fig_map.canvas.flush_events()

    # ref: https://matplotlib.org/3.1.1/gallery/ticks_and_spines/colorbar_tick_labelling_demo.html
    # bar.ax.set_yticklabels(
    #     labels=bar.ax.get_yticklabels(),
    #     fontsize=50, weight='bold'
    # )

    bar.set_label(label="(degC)", size=11, weight='bold')

    ax.set_title(fig_title, fontsize=12, weight='bold', loc='center')

    return fig_map
Exemplo n.º 32
0
fig, ax = plt.subplots(1, 1)
ax.hist(phase_rot.ravel())
ax.set_title(
    'Gridded: Mask - 0 = Cloud,1 = 66% prob.\n Clear,2 = 95% prob. Clear,3 = 99% prob. Clear'
)

# In[112]:

plt.close('all')
from matplotlib.colors import Normalize
from numpy import ma
fig, ax = plt.subplots(1, 1, figsize=(12, 12))
colors = sns.color_palette('coolwarm')
pal = LinearSegmentedColormap.from_list('test', colors)
pal.set_bad('0.75')  #75% grey
pal.set_over('r')
pal.set_under('k')
vmin = -5.
vmax = 5.
ch29 = np.rot90(file_dict['ch29'], 2)
ch31 = np.rot90(file_dict['ch31'], 2)
the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
tdiff = ch31 - ch29
tdiff = ma.array(tdiff, mask=np.isnan(tdiff))
CS = ax.imshow(tdiff, cmap=pal, norm=the_norm)
cax = plt.colorbar(CS, ax=ax, extend='both')
cax.set_label('ch31 - ch29 brightnes temp (K)')
ax.set_title('TB 11 micron - TB 8 micron')

# ### For next Tuesday: check in a notebook that
#
Exemplo n.º 33
0
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options):
    r"""
    ``region_plot`` takes a boolean function of two variables, `f(x,y)`
    and plots the region where f is True over the specified 
    ``xrange`` and ``yrange`` as demonstrated below.

    ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)``

    INPUT:

    - ``f`` -- a boolean function of two variables

    - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple
      ``(x,xmin,xmax)``

    - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple
      ``(y,ymin,ymax)``

    - ``plot_points``  -- integer (default: 100); number of points to plot
      in each direction of the grid

    - ``incol`` -- a color (default: ``'blue'``), the color inside the region

    - ``outcol`` -- a color (default: ``'white'``), the color of the outside
      of the region

    If any of these options are specified, the border will be shown as indicated,
    otherwise it is only implicit (with color ``incol``) as the border of the 
    inside of the region.

     - ``bordercol`` -- a color (default: ``None``), the color of the border
       (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``)

    - ``borderstyle``  -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot'

    - ``borderwidth``  -- integer (default: None), the width of the border in pixels
 
    - ``legend_label`` -- the label for this item in the legend


    EXAMPLES:

    Here we plot a simple function of two variables::

        sage: x,y = var('x,y')
        sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3))
         
    Here we play with the colors::

        sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray')
        
    An even more complicated plot, with dashed borders::

        sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250)

    A disk centered at the origin::

        sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1))

    A plot with more than one condition (all conditions must be true for the statement to be true)::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2))

    Since it doesn't look very good, let's increase ``plot_points``::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400)

    To get plots where only one condition needs to be true, use a function.
    Using lambda functions, we definitely need the extra ``plot_points``::

        sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400)
    
    The first quadrant of the unit circle::

        sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400)

    Here is another plot, with a huge border::

        sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50)

    If we want to keep only the region where x is positive::

        sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50)

    Here we have a cut circle::

        sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200)

    The first variable range corresponds to the horizontal axis and
    the second variable range corresponds to the vertical axis::

        sage: s,t=var('s,t')
        sage: region_plot(s>0,(t,-2,2),(s,-2,2))

    ::

        sage: region_plot(s>0,(s,-2,2),(t,-2,2))

    """

    from sage.plot.plot import Graphics
    from sage.plot.misc import setup_for_eval_on_grid
    import numpy

    if not isinstance(f, (list, tuple)):
        f = [f]

    f = [equify(g) for g in f]

    g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points)
    xrange,yrange=[r[:2] for r in ranges]

    xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)]
                                     for y in xsrange(*ranges[1], include_endpoint=True)]
                                    for func in g],dtype=float)
    xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0))
    # Now we need to set entries to negative iff all
    # functions were negative at that point.
    neg_indices = (xy_data_arrays<0).all(axis=0)
    xy_data_array[neg_indices]=-xy_data_array[neg_indices]

    from matplotlib.colors import ListedColormap
    incol = rgbcolor(incol)
    outcol = rgbcolor(outcol)
    cmap = ListedColormap([incol, outcol])
    cmap.set_over(outcol)
    cmap.set_under(incol)
    
    g = Graphics()
    g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax']))
    g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, 
                                dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options)))

    if bordercol or borderstyle or borderwidth:
        cmap = [rgbcolor(bordercol)] if bordercol else ['black']
        linestyles = [borderstyle] if borderstyle else None
        linewidths = [borderwidth] if borderwidth else None
        g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, 
                                    dict(linestyles=linestyles, linewidths=linewidths,
                                         contours=[0], cmap=[bordercol], fill=False, **options)))
    
    return g
Exemplo n.º 34
0
def plot_rwr_map(ax,
                 grid,
                 var,
                 bad=None,
                 title=None,
                 levs=None,
                 cmap=None,
                 ocean=None,
                 labelled=False,
                 add_hist=True,
                 add_colorbar=False):
    """
    Make a standard global RWR map.

    Parameters
    ----------

    ax : <matplotlib.axes.Axes> instance.
        The axes to which the map will be drawn.
    grid : <geo_grid.LandGrid> instance
        Object describing the RWR spatial grid.
    var : <numpy.ma.MaskedArray> instance, shape(lat, lon).
        RWR data to plot on the map and histogram.
    bad : <numpy.array> instance, shape(lat, lon), optional.
        Array defining grid boxes that will be greyed-out, e.g., where
        var is poorly estimated.
    title : str, optional
        Text to replace the standard plot title.
    levs : list, optional
        Tick levels to use on the colorbar.  Currently this is only used
        to normalise the data between [min(levs), max(levs)] for plotting.
    cmap : str or <matplotlib.colors.Colormap> instance, optional
        Colormap or colormap name.
    ocean : Matplotlib color, optional
        Color to mask the ocean.
    labelled : bool, optional
        If True, draw lon/lat gridlines and labels on the map.
    add_hist : bool, optional
        If True, a histogram of the data is added to the map.
    add_colorbar : bool, optional
        If True, a colorbar is added stealing from axes ax.

    Returns
    -------

    PCM : mappable
        E.,g, <matplotlib.collections.QuadMesh>

    """

    if title is None:
        title = "Dry spell RWR (°C day⁻¹)"

    if levs is None:
        levs = np.linspace(-0.27, 0.27, 10).tolist()

    if cmap is None:
        cmap = ListedColormap([
            '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#f7f7f7', '#d1e5f0',
            '#92c5de', '#4393c3', '#2166ac'
        ][::-1])

        cmap.set_over('darkred')
        cmap.set_under('darkblue')

    if add_colorbar:
        cmap.colorbar_extend = "both"
        ticks = levs[:4] + [
            0.0,
        ] + levs[-4:]
    else:
        ticks = None

    PCM = _plot_map(ax,
                    grid,
                    var,
                    levs,
                    cmap,
                    ticks=ticks,
                    labelled=labelled,
                    ocean=ocean)

    ax.set_title(title, fontsize=12)

    if bad is not None:
        kw_plot_greyed = {
            "cmap": ListedColormap([
                "0.5",
            ]),
        }
        greyed = np.ma.ones(bad.shape, dtype=int)
        greyed.mask = ~bad
        I2 = grid.plot_var(ax, greyed, labelled=False, kw_plot=kw_plot_greyed)

    if add_hist:
        bx = _plot_hist(ax, var, cmap, bad=bad)

    return PCM
Exemplo n.º 35
0
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol,
                borderstyle, borderwidth, **options):
    r"""
    ``region_plot`` takes a boolean function of two variables, `f(x,y)`
    and plots the region where f is True over the specified
    ``xrange`` and ``yrange`` as demonstrated below.

    ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)``

    INPUT:

    - ``f`` -- a boolean function of two variables

    - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple
      ``(x,xmin,xmax)``

    - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple
      ``(y,ymin,ymax)``

    - ``plot_points``  -- integer (default: 100); number of points to plot
      in each direction of the grid

    - ``incol`` -- a color (default: ``'blue'``), the color inside the region

    - ``outcol`` -- a color (default: ``'white'``), the color of the outside
      of the region

    If any of these options are specified, the border will be shown as indicated,
    otherwise it is only implicit (with color ``incol``) as the border of the
    inside of the region.

     - ``bordercol`` -- a color (default: ``None``), the color of the border
       (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``)

    - ``borderstyle``  -- string (default: 'solid'), one of ``'solid'``,
      ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``,
      ``'--'``, ``':'``, ``'-.'``.

    - ``borderwidth``  -- integer (default: None), the width of the border in pixels

    - ``legend_label`` -- the label for this item in the legend

    - ``base`` - (default: 10) the base of the logarithm if
      a logarithmic scale is set. This must be greater than 1. The base
      can be also given as a list or tuple ``(basex, basey)``.
      ``basex`` sets the base of the logarithm along the horizontal
      axis and ``basey`` sets the base along the vertical axis.

    - ``scale`` -- (default: ``"linear"``) string. The scale of the axes.
      Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``,
      ``"semilogy"``.

      The scale can be also be given as single argument that is a list
      or tuple ``(scale, base)`` or ``(scale, basex, basey)``.

      The ``"loglog"`` scale sets both the horizontal and vertical axes to
      logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis
      to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis
      to logarithmic scale. The ``"linear"`` scale is the default value
      when :class:`~sage.plot.graphics.Graphics` is initialized.


    EXAMPLES:

    Here we plot a simple function of two variables::

        sage: x,y = var('x,y')
        sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3))
        Graphics object consisting of 1 graphics primitive

    Here we play with the colors::

        sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray')
        Graphics object consisting of 2 graphics primitives

    An even more complicated plot, with dashed borders::

        sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250)
        Graphics object consisting of 2 graphics primitives

    A disk centered at the origin::

        sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1))
        Graphics object consisting of 1 graphics primitive

    A plot with more than one condition (all conditions must be true for the statement to be true)::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2))
        Graphics object consisting of 1 graphics primitive

    Since it doesn't look very good, let's increase ``plot_points``::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400)
        Graphics object consisting of 1 graphics primitive

    To get plots where only one condition needs to be true, use a function.
    Using lambda functions, we definitely need the extra ``plot_points``::

        sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400)
        Graphics object consisting of 1 graphics primitive

    The first quadrant of the unit circle::

        sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400)
        Graphics object consisting of 1 graphics primitive

    Here is another plot, with a huge border::

        sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50)
        Graphics object consisting of 2 graphics primitives

    If we want to keep only the region where x is positive::

        sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50)
        Graphics object consisting of 1 graphics primitive

    Here we have a cut circle::

        sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200)
        Graphics object consisting of 2 graphics primitives

    The first variable range corresponds to the horizontal axis and
    the second variable range corresponds to the vertical axis::

        sage: s,t=var('s,t')
        sage: region_plot(s>0,(t,-2,2),(s,-2,2))
        Graphics object consisting of 1 graphics primitive

    ::

        sage: region_plot(s>0,(s,-2,2),(t,-2,2))
        Graphics object consisting of 1 graphics primitive

    An example of a region plot in 'loglog' scale::

        sage: region_plot(x^2+y^2<100, (x,1,10), (y,1,10), scale='loglog')
        Graphics object consisting of 1 graphics primitive

    """

    from sage.plot.all import Graphics
    from sage.plot.misc import setup_for_eval_on_grid
    import numpy

    if not isinstance(f, (list, tuple)):
        f = [f]

    f = [equify(g) for g in f]

    g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points)
    xrange, yrange = [r[:2] for r in ranges]

    xy_data_arrays = numpy.asarray(
        [[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)]
          for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],
        dtype=float)
    xy_data_array = numpy.abs(xy_data_arrays.prod(axis=0))
    # Now we need to set entries to negative iff all
    # functions were negative at that point.
    neg_indices = (xy_data_arrays < 0).all(axis=0)
    xy_data_array[neg_indices] = -xy_data_array[neg_indices]

    from matplotlib.colors import ListedColormap
    incol = rgbcolor(incol)
    outcol = rgbcolor(outcol)
    cmap = ListedColormap([incol, outcol])
    cmap.set_over(outcol)
    cmap.set_under(incol)

    g = Graphics()

    # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'.
    # Otherwise matplotlib complains.
    scale = options.get('scale', None)
    if isinstance(scale, (list, tuple)):
        scale = scale[0]
    if scale == 'semilogy' or scale == 'semilogx':
        options['aspect_ratio'] = 'automatic'

    g._set_extra_kwds(
        Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax']))
    g.add_primitive(
        ContourPlot(
            xy_data_array, xrange, yrange,
            dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True,
                 **options)))

    if bordercol or borderstyle or borderwidth:
        cmap = [rgbcolor(bordercol)] if bordercol else ['black']
        linestyles = [borderstyle] if borderstyle else None
        linewidths = [borderwidth] if borderwidth else None
        g.add_primitive(
            ContourPlot(
                xy_data_array, xrange, yrange,
                dict(linestyles=linestyles,
                     linewidths=linewidths,
                     contours=[0],
                     cmap=[bordercol],
                     fill=False,
                     **options)))

    return g
                 1.055 * np.power(var_G, power) - 0.055)
var_B = np.where(var_B <= 0.0031308, var_B * 12.92,
                 1.055 * np.power(var_B, power) - 0.055)

sR = var_R * 255
sG = var_G * 255
sB = var_B * 255

# Create custom colormap from sRGB list and plot the colormap.
# This is the easiest way to create a visualisation that looks like a
# drilling core. Take note that the figure does not take into account any
# gaps in a record and will produce a continous record. I suggest to fill all
# gaps either by white (CIE Lab: 100 0 0) or interpolate the gaps with the
# values above and below.

zipped = zip(var_R, var_G, var_B)
sRGB_list = list(zipped)

fig = plt.figure()
ax = fig.subplots()
cmap = ListedColormap(sRGB_list)
cmap.set_over('0.25')
cmap.set_under('0.75')
bounds = np.arange(0, cmap.N, 1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax, cmap=cmap, orientation='horizontal')
cb2.set_label('')
cb2.outline.set_visible(False)
cb2.set_ticks([])
ax.set_xticklabels('')
plt.savefig('colormap_core.png', dpi=600)