Ejemplo n.º 1
0
    def __init__(self, config=None):
        if config is None:
            config = SectionPlotConfig()

        self.config = config
        self._disconnect_data = []
        self._width = self._height = self._pixels = None
        self._plt = plot.mpl_init(self.config.font_size)
        self._fig = fig = self._plt.figure(figsize=self.config.size_inch)

        rect = [0., 0., 1., 1.]
        self._axes_xy = Axes(fig, rect)
        self._axes_xz = Axes(fig, rect)
        self._axes_zy = Axes(fig, rect)

        self._view_limits = num.zeros((3, 2))

        self._view_limits[:, :] = num.nan

        self._update_geometry()

        for axes in self.axes_list:
            fig.add_axes(axes)
            self._connect(axes, 'xlim_changed', self.lim_changed_handler)
            self._connect(axes, 'ylim_changed', self.lim_changed_handler)

        self._cid_resize = fig.canvas.mpl_connect('resize_event',
                                                  self.resize_handler)

        self._connect(fig, 'dpi_changed', self.dpi_changed_handler)

        self._lim_changed_depth = 0
Ejemplo n.º 2
0
    def __init__(self, ax, cview_args={}, display_args={}, colormap=[]):

        cview_ax = Axes(ax.get_figure(), ax.get_position(original=True))
        cmap_ax = Axes(ax.get_figure(), ax.get_position(original=True))

        self.ax = ax
        self.cview = ColorViewer(cview_ax, **cview_args)
        self.colormap = MapDisplay(cmap_ax, self.cview, **display_args)
        for name, color in colormap:
            self.colormap.add_item(name, color)

        divider = make_axes_locatable(ax)
        pad = Size.Fixed(0.1)
        colormap_width = Size.Fraction(0.29, Size.AxesX(ax))
        cview_width = Size.Fraction(0.7, Size.AxesX(ax))
        divider.set_horizontal([colormap_width, pad, cview_width])

        cmap_ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
        ax.figure.add_axes(cmap_ax)

        cview_ax.set_axes_locator(divider.new_locator(nx=2, ny=0))
        ax.figure.add_axes(cview_ax)

        ax.tick_params(left=False,
                       bottom=False,
                       labelleft=False,
                       labelbottom=False)
        ax.set_axis_off()
Ejemplo n.º 3
0
    def __init__(self, draw, data, ax_kwargs={},
                 dpi=50, frameon=False, figsize=[8, 6],
                 transparent=False, axes_off=True):

        super().__init__(dpi=dpi, frameon=frameon, figsize=figsize)
        ax = Axes(self, [0., 0., 1., 1.])
        if axes_off:
            ax.set_axis_off()

        result = draw(**data, **ax_kwargs, ax=ax)

        # if draw function only returns the axes
        if isinstance(result, Axes):
            ax = result
        else:
            (ax, self.x_lim, self.y_lim) = result[0:3]
            if len(result) > 3:
                self.other_returns = result[3:]

        self.add_axes(ax)

        self.buffer = io.BytesIO()
        self.savefig(self.buffer,
                     transparent=transparent, dpi=dpi,
                     pad_inches=0, format='png')
Ejemplo n.º 4
0
    def set_colorbar(self, vmin: float, vmax: float, cmap="viridis", norm=None, label: str = None):
        """
        Create a colorbar and display the figure in the colorbar widget
        Args:
            vmin: Minimun value of the colorbar
            vmax: Maximum value of the colorbar
            cmap: Colormap of the colorbar
            norm: (optionl) Normalization, in case that not, this is internally managed
            label: Text to display as label in the colorbar
        Returns:

        """
        if self.colorbar is not None:
            if isinstance(cmap, str):
                cmap = plt.get_cmap(cmap)
            label = label if label is not None else self._label
            cb = Figure()
            ax = Axes(cb, self._dim_label_ax)
            cb.add_axes(ax)
            norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) if norm is None else norm
            cb1 = matplotlib.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation=self.pos_colorbar)
            cb1.set_label(label, size=self._size_label_cbar) if label is not None else None
            cb1.ax.tick_params(labelsize=self._size_label_cbar)
            self.colorbar.object = cb
            self.colorbar.param.trigger("object")
    def __init__(self, selection, font_sz = 8, pad = 4, legend = None):

        self._selection = selection
        self._ax = Axes(selection._graph.ax.get_figure(), selection._graph.ax.get_position(original = True))

        self._legend = legend

        button_sz = 1.0 / (self._ax.figure.get_dpi() / (font_sz + pad))
        n_rows, pad_sz = 5, 0.02
        rows = [ i * (button_sz + pad_sz) for i in range(n_rows) ]

        self._actions = {
            "hide": Option(self._ax, (0.0, rows[4]), 0.49, button_sz, font_sz, "hide selection", self._hide_selection),
            "restore": Option(self._ax, (0.51, rows[4]), 0.49, button_sz, font_sz, "restore selection", self._restore_selection),
            "in": Toggle(self._ax, (0.0, rows[3]), 0.49, button_sz, font_sz, self._toggle_in_neighbors, "hide in neighbors", "restore in neighbors"),
            "out": Toggle(self._ax, (0.51, rows[3]), 0.49, button_sz, font_sz, self._toggle_out_neighbors, "hide out neighbors", "restore out neighbors"),
            "complement": Toggle(self._ax, (0.0, rows[2]), 1.0, button_sz, font_sz, self._toggle_complement, "hide others", "restore others"),
            "remove": Option(self._ax, (0.0, rows[1]), 1.0, button_sz, font_sz, "remove selection", self._remove_selection),
            "deselect": Option(self._ax, (0.0, rows[0]), 1.0, button_sz, font_sz, "deselect all", self._deselect_all),
        }

        self._ax.tick_params(left = False, labelleft = False, bottom = False, labelbottom = False)
        self._ax.set_frame_on(False)
        self._ax.set_anchor("NW")
        self._ax.set_ylim(0, n_rows * button_sz + (n_rows - 1) * pad_sz)
Ejemplo n.º 6
0
    def __init__(self, graph, selection):

        self._graph = graph
        self._selection = selection
        self._groups = []
        self._ax = Axes(self._graph.ax.get_figure(),
                        self._graph.ax.get_position(original=True))
    def __init__(self, graph, font_sz=8, pad=4):

        self._graph = graph
        self._ax = Axes(graph.ax.get_figure(),
                        graph.ax.get_position(original=True))

        button_sz = 1.0 / (self._ax.figure.get_dpi() / (font_sz + pad))
        n_rows, pad_sz = len(graph.press_actions), 0.02
        rows = [i * (button_sz + pad_sz) for i in range(n_rows)]

        self._actions = {}
        for name, row in zip(graph.press_actions, rows):
            action = self._set_action(name)
            self._actions[name] = Toggle(self._ax, (0.0, row), 1.0, button_sz,
                                         font_sz, action, name)

        current = graph._press_action
        self._actions[current]._set_pressed()

        self._ax.tick_params(left=False,
                             labelleft=False,
                             bottom=False,
                             labelbottom=False)
        self._ax.set_frame_on(False)
        self._ax.set_anchor("NW")
        self._ax.set_ylim(0, n_rows * button_sz + (n_rows - 1) * pad_sz)
Ejemplo n.º 8
0
def configure_axes(figure, rect=None, _=None):

    axes = Axes(figure, rect or [0, 0, 1, 1])

    figure.add_axes(axes)

    return axes
Ejemplo n.º 9
0
    def _process(self, element, key=None):
        try:
            from matplotlib.contour import QuadContourSet
            from matplotlib.axes import Axes
            from matplotlib.figure import Figure
        except ImportError:
            raise ImportError("contours operation requires matplotlib.")
        extent = element.range(0) + element.range(1)[::-1]

        if type(element) is Raster:
            data = [np.flipud(element.data)]
        elif isinstance(element, Image):
            data = [np.flipud(element.dimension_values(2, flat=False))]
        elif isinstance(element, QuadMesh):
            data = (element.dimension_values(0, False),
                    element.dimension_values(1, False), element.data[2])

        if isinstance(self.p.levels, int):
            levels = self.p.levels + 1 if self.p.filled else self.p.levels
            zmin, zmax = element.range(2)
            levels = np.linspace(zmin, zmax, levels)
        else:
            levels = self.p.levels

        xdim, ydim = element.dimensions('key', label=True)
        fig = Figure()
        ax = Axes(fig, [0, 0, 1, 1])
        contour_set = QuadContourSet(ax,
                                     *data,
                                     filled=self.p.filled,
                                     extent=extent,
                                     levels=levels)
        if self.p.filled:
            contour_type = Polygons
            levels = np.convolve(levels, np.ones((2, )) / 2, mode='valid')
        else:
            contour_type = Contours
        vdims = element.vdims[:1]

        paths = []
        for level, cset in zip(levels, contour_set.collections):
            for path in cset.get_paths():
                if path.codes is None:
                    subpaths = [path.vertices]
                else:
                    subpaths = np.split(path.vertices,
                                        np.where(path.codes == 1)[0][1:])
                for p in subpaths:
                    paths.append({
                        (xdim, ydim): p,
                        element.vdims[0].name: level
                    })
        contours = contour_type(paths,
                                label=element.label,
                                kdims=element.kdims,
                                vdims=vdims)
        if self.p.overlaid:
            contours = element * contours
        return contours
Ejemplo n.º 10
0
    def get_contours(self):
        from matplotlib.contour import QuadContourSet
        from matplotlib.axes import Axes
        from matplotlib.figure import Figure

        # Use method matplotlib
        fig = Figure()
        ax = Axes(fig, [0, 0, 1, 1])
        # Get extent
        if self.dic:
            extent=(self.x0_ppm, self.x1_ppm, self.y0_ppm, self.y1_ppm)
        else:
            extent=None
        # calculate contour levels
        cl = self.get_contour_levels()
        # Get contours
        contour_set = QuadContourSet(ax, self.data, filled=False, extent=extent, levels=cl)

        # To plot in bokeh
        xs = []
        ys = []
        intensity = []
        xt = []
        yt = []
        col = []
        text = []
        isolevelid = 0
        color_palettes = bp.viridis(len(cl))
        for level, isolevel in zip(cl, contour_set.collections):
            level_round = round(level, 2)
            #theiso = str(contour_set.get_array()[isolevelid])
            theiso = str(level_round)
            # Get colour
            #isocol = isolevel.get_color()[0]
            #thecol = 3 * [None]
            #for i in range(3):
            #    thecol[i] = int(255 * isocol[i])
            #thecol = '#%02x%02x%02x' % (thecol[0], thecol[1], thecol[2])
            thecol = color_palettes[isolevelid]

            for path in isolevel.get_paths():
                v = path.vertices
                x = v[:, 0]
                y = v[:, 1]
                xs.append(x.tolist())
                ys.append(y.tolist())
                intensity.append(level)
                xt.append(x[int(len(x) / 2)])
                yt.append(y[int(len(y) / 2)])
                text.append(theiso)
                col.append(thecol)
            # Add to counter
            isolevelid += 1
        cdata={'xs': xs, 'ys': ys, 'line_color': col, 'intensity': intensity}
        ctext={'xt':xt,'yt':yt,'text':text}
        return cdata, ctext
Ejemplo n.º 11
0
 def figure(self, key):
     style = self[key]
     figure = Figure(figsize=(0.1, 0.1))  # TODO: hardcoded
     axes = Axes(figure, [0, 0, 1, 1], yticks=[], xticks=[], frame_on=False)
     figure.add_axes(axes)
     axes.patch.set_visible(False)
     marker_style = style.point_style()
     marker_style["s"] = 40 # Reset size
     axes.scatter(0, 0, **marker_style)
     return figure
Ejemplo n.º 12
0
 def figure(self, name):
     from matplotlib.axes import Axes
     style = self[name]
     plt.figure(figsize=(0.1, 0.1)) # TODO: hardcoded
     ax = Axes(plt.gcf(), [0, 0, 1, 1], yticks=[], xticks=[], frame_on=False)
     plt.gcf().delaxes(plt.gca())
     plt.gcf().add_axes(ax)
     #plt.axis('off')
     plt.scatter(0, 0, marker=style["marker"], c=[style["color"]])
     plt.autoscale(tight=True)
Ejemplo n.º 13
0
def create_and_prepare_axes(figure, extent, **kwargs):
    # import matplotlib.figure.Figure.text
    ax = Axes(figure, extent)  # , label=kwargs.get('toc_uid', ''))
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.xaxis.set_major_locator(NullLocator())
    ax.yaxis.set_major_locator(NullLocator())
    figure.add_axes(ax)
    return ax
Ejemplo n.º 14
0
    def __init__(self, ax):

        self.ax = Axes(ax.get_figure(), ax.get_position(original=True))
        self.ax.set_aspect("equal")
        self.ax.set_anchor("NE")

        self._visible_vertices, self._visible_edges = {}, {}
        self._hidden_vertices, self._hidden_edges = {}, {}

        self._press_action = "move"
        self._press_actions = {
            "move": None,
        }
Ejemplo n.º 15
0
    def __init__(self, extent: list = None, **kwargs):
        """Importing packages and setting correctly the path to the devito package, this beacuse we need the examples"""
        self.Load_Area = LoadSaveTopoModule(extent=extent, **kwargs)
        self.vp = None  # Normalized or smoothed or None topography to be the velocity model
        self.model: Model = None  # the model
        self.time_range = None  # the time of the simulation
        self.src = None  # the ricker source
        self.u = None  # wavefield time function
        self.pde = None  # PDE to solve. Wave equation with corresponding discretizations
        self.stencil = None  # a time marching updating equation known as a stencil using customized SymPy functions
        self.src_coordinates = []
        self.src_term = []  # all sources together
        self.rec = None
        self.rec_term = []  # all receivers

        # After constructing all the necessary expressions for updating the wavefield,
        # injecting the source term and interpolating onto the receiver points, we can now create the Devito operator
        self.op = None
        self.n_frames_speed = 10
        self.frequency = 0.025  # Source peak frequency is 25Hz (0.025 kHz)
        # self.aruco_sources_coord = []
        # For the cropping, because when normalizing the velocities dont work
        self.crop = True
        self.xy_aruco = []
        # for the plotting
        self.timeslice = 0
        self.threshold = 0.03
        self.field = None

        self.p_velocity = True
        self.ready_velocity = False
        self.p_wave = True
        self.ready_wave = False

        self.framerate = 10
        self._vp = None
        self._w = None
        self.real_time = False
        self.model_extent = None
        self.frame = None
        self.extent = None
        self.max_wave_frame = 1

        # Widgets
        self.lock = None
        self.figure = Figure()
        self.axes = Axes(self.figure, [0., 0., 1., 1.])
        self.figure.add_axes(self.axes)
        self.panel_figure = pn.pane.Matplotlib(self.figure, tight=True)
        plt.close(self.figure)  # close figure to prevent inline display
        logger.info("SeismicModule loaded successfully")
Ejemplo n.º 16
0
def inset_axes(self,
               bounds,
               *,
               polar=True,
               transform=None,
               zorder=5,
               **kwargs):
    """ Serves as a stand-in for Axes.inset_axes, but also allows polar projection

    Args:
        self (Axes): Axes object
        bounds (list): (x, y, xsize, ysize)
        polar (bool): polar projection
        transform (Transfomr): Defaults to `ax.transAxes`, i.e. the units of *rect* are in
            axes-relative coordinates.
        zorder (int): Defaults to 5 (same as `.Axes.legend`).  Adjust higher or lower
            to change whether it is above or below data plotted on the
            parent axes.
        **kwargs: Other *kwargs* are passed on to the `axes.Axes` child axes.

    Returns:
        Axes - The created `.axes.Axes` instance.
    """
    if transform is None:
        transform = self.transAxes
    label = kwargs.pop('label', 'inset_axes')

    # This puts the rectangle into figure-relative coordinates.
    inset_locator = _make_inset_locator(bounds, transform, self)
    bb = inset_locator(None, None)

    if polar:
        inset_ax = PolarAxes(self.figure,
                             bb.bounds,
                             zorder=zorder,
                             label=label,
                             **kwargs)
    else:
        inset_ax = Axes(self.figure,
                        bb.bounds,
                        zorder=zorder,
                        label=label,
                        **kwargs)

    # this locator lets the axes move if in data coordinates.
    # it gets called in `ax.apply_aspect() (of all places)
    inset_ax.set_axes_locator(inset_locator)

    self.add_child_axes(inset_ax)

    return inset_ax
Ejemplo n.º 17
0
def preview(path, ext=0, width=None, minwidth=256, maxwidth=1024):
    """
    Preview FITS image as PNG
    """
    base = stdconf.get('basepath', '.')
    fullpath = os.path.join(base, path)

    # Optional parameters
    fmt = request.args.get('format', 'jpeg')
    quality = int(request.args.get('quality', 80))

    width = request.args.get('width', width)
    if width is not None:
        width = int(width)

    data = fits.getdata(fullpath, ext)

    figsize = [data.shape[1], data.shape[0]]

    if width is None:
        if figsize[0] < minwidth:
            width = minwidth
        elif figsize[0] > maxwidth:
            width = maxwidth

    if width is not None and figsize[0] != width:
        figsize[1] = width*figsize[1]/figsize[0]
        figsize[0] = width

    fig = Figure(facecolor='white', dpi=72, figsize=(figsize[0]/72, figsize[1]/72))
    ax = Axes(fig, [0., 0., 1., 1.])
    # ax.set_axis_off()
    fig.add_axes(ax)
    plots.imshow(data, ax=ax, show_axis=False, show_colorbar=False,
                 cmap=request.args.get('cmap', 'Blues_r'),
                 stretch=request.args.get('stretch', 'linear'),
                 qq=[float(request.args.get('qmin', 0.5)), float(request.args.get('qmax', 99.5))])

    if request.args.get('ra', None) is not None and request.args.get('dec', None) is not None:
        # Show the position of the object
        header = fits.getheader(fullpath, ext)
        wcs = WCS(header)
        x,y = wcs.all_world2pix(float(request.args.get('ra')), float(request.args.get('dec')), 0)
        ax.add_artist(Circle((x, y), 5.0, edgecolor='red', facecolor='none', ls='-', lw=2))

    buf = io.BytesIO()
    fig.savefig(buf, format=fmt, quality=quality)

    return Response(buf.getvalue(), mimetype='image/%s' % fmt)
Ejemplo n.º 18
0
def inset_axes(parent_axes, width, height, loc=1,
               bbox_to_anchor=None, bbox_transform=None,
               axes_class=None,
               axes_kwargs=None,
               **kwargs):

   if axes_class is None:
      axes_class = Axes

   if axes_kwargs is None:
      inset_axes = Axes(parent_axes.figure, parent_axes.get_position())
   else:
      inset_axes = Axes(parent_axes.figure, parent_axes.get_position(),
                        **axes_kwargs)

   axes_locator = AnchoredSizeLocator(parent_axes.bbox,
                                      width, height,
                                      loc=loc)

   inset_axes.set_axes_locator(axes_locator)

   _add_inset_axes(parent_axes, inset_axes)

   return inset_axes
Ejemplo n.º 19
0
    def __init__(self,
                 numbers,
                 left_labels = None,
                 right_labels = None, # 'proportion' 'rank'
                 colors = None,
                 line_dic = None,
                 sort = False,
                 slice = None, # one-based indexing
                 global_view = False,
                 auto_scale = False,
                 color_dic = None,
                 title = None,
                 xlabel = None,
                 ylabel = None,
                 legend_title = None,
                 legend_visible = True,
                 file_name = None,
                 **kwargs):
        """
        The data space can adapt to long labels but only to
        some extent because the long label sizes are fixed.
        This class moves the edges of the axes to make room
        for labels (SEE Matplotlib HOW-TOs).
        """                        
        if 'log_level' in kwargs:
            logging.basicConfig(format='{levelname}:\n{message}',
                                level= getattr(logging, kwargs['log_level']),
                                style = '{')
            
        # Configuration: matplotlibrc is decorated by conf.py.
        self.conf = Conf.change_conf(kwargs)
        
        # Data formatted by the model.
        self.data = None
        
        
        # Core Matplotlib objects.
        self.fig = None
        self.ax = None
        self.canvas = None
        self.vertical_line = None
        self.bars = None # BarContainer.
        self._virtual_bars  = None # For global_view.

        # Helper attributes.
        self._left_label_data = None
        self._right_label_texts = None
        
        # Titles.
        self.title = title
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.legend_title = legend_title
        
        self._global_view = global_view
        self.legend = None
        self._legend_width = 0
        self.legend_visible = legend_visible
        
        # The vertical line.        
        self.line_x = None
        self.line_label = None
        self.line_color = None
        
        
        # Original position of the axes edges in the figure.
        self._x0 = 0
        self._y0 = 0
        self._width = 1
        self._height = 1



        # To deal with not square figures,
        # only x sizes are adapted.
        self._x_coeff = 1

        

        #########################################################

        # Model.
        factory = ModelFactory(
            numbers,
            global_view = global_view,
            left_labels = left_labels,
            right_labels = right_labels,
            colors = colors,
            sort = sort,
            slice = slice,
            default_label = self.conf['default_label'],
            color_dic = color_dic,
            tints = self.conf['tints'],
            default_color = self.conf['default_color'])
        


        self.data = factory.model
                        
        
        self.fig = Figure(figsize = self.conf['figsize'],
                          dpi = self.conf['dpi'])
        
        self.canvas = FigureCanvasAgg(self.fig)
        
        
        self.ax = Axes(self.fig,
                       [self._x0,
                        self._y0,
                        self._width,
                        self._height])
        
        
        self.fig.add_axes(self.ax)
        self.canvas.draw()
       
        w, h = self.fig.get_size_inches()
        self._x_coeff = h / w
        
        # margin.
        margin = self.conf['margin']
        
        self._x0 = self._x_coeff * margin
        self._y0 = margin
        self._width = self._width - 2 * self._x_coeff * margin
        self._height = self._height - 2 * margin
        
        self._set_position()

                
        self.ax.tick_params(axis = 'y',
                            length = 0)
        
        self.ax.grid(b = True,
                     axis = 'x',
                     which = 'both',
                     color = 'black',
                     alpha = 0.3)
        
        
        for name in ['top', 'right']:
            self.ax.spines[name].set_visible(False)
        
        # xscale.
        if auto_scale is True:
            # To improve clarity.
            if self.data.spread > 1 or self.data.maximum > 1e6:
                self.ax.set(xscale = 'log')
        else:
            default_formatter = self.ax.get_xaxis().get_major_formatter()
            custom_formatter = self.build_formatter(default_formatter)
            formatter = matplotlib.ticker.FuncFormatter(custom_formatter)
            self.ax.get_xaxis().set_major_formatter(formatter)
        
        
        # Title.
        if self.title is not None:
            self._manage_title()

        
        _kwargs = dict()

        # Left labels.
        if self.data.left_labels is not None:
            _kwargs['tick_label'] = self.data.left_labels 
        else:
            _kwargs['tick_label'] = ''

        # colors.
        if self.data.actual_colors is not None:
            _kwargs['color'] = self.data.actual_colors
        else:
            _kwargs['color'] = self.data.default_color

        # bars.
        self.bars = self.ax.barh(list(range(self.data.length)),
                                 self.data.numbers,
                                 height = 1,
                                 edgecolor = 'white',
                                 linewidth = 1, # 0.4
                                 alpha = self.conf['color_alpha'],
                                 **_kwargs)

        # To fix x bounds, virtual bars are used.
        if self._global_view is True:
            self._virtual_bars = self.ax.barh(
                [0, 0],
                [self.data.minimum,
                 self.data.maximum],
                height = 0.5,
                edgecolor = 'white',
                linewidth = 1, # 0.4
                alpha = self.conf['color_alpha'],
                visible = False)

        
        # The vertical line.
        if line_dic is not None:
            self._set_line(line_dic)
        
            if (self.line_x is not None and
                self.data.minimum <= self.line_x <= self.data.maximum):
                #
                self.vertical_line = self.ax.axvline(
                    self.line_x,
                    ymin = 0,
                    ymax = 1,
                    color = self.line_color,
                    linewidth = 2,
                    alpha = self.conf['color_alpha'])
        

        # Left label constraint solving.
        self._make_room_for_left_labels()

        # ylabel.
        if self.ylabel is not None:
            self._manage_ylabel()
        
        
        # Legend.
        if (self.legend_visible is True and
            self.data.colors is not None):
            #
            self._draw_legend()
            self._make_room_for_legend()
        
        
        # Right labels.
        if self.data.right_labels is not None:
            self._draw_right_labels()            
            self._make_room_for_right_labels()
        
        
        min_tick_y = self._clean_x_ticklabels()
        
        # xlabel.
        if self.xlabel is not None:
            self._manage_xlabel(min_tick_y)
        else:
            delta_y0 = abs(self._y0 - min_tick_y)
            self._y0 = self._y0 + delta_y0
            self._height = self._height - delta_y0
            self._set_position()

        
        self.canvas.draw()
        
        # Printing.
        if file_name is not None:
            self.canvas.print_png(file_name)
Ejemplo n.º 20
0
def plot_hex_and_violin(abscissa,
                        ordinate,
                        bin_edges,
                        extent=None,
                        xlabel="",
                        ylabel="",
                        zlabel="",
                        do_hex=True,
                        do_violin=True,
                        cm=plt.cm.inferno,
                        axis=None,
                        v_padding=.015,
                        **kwargs):
    """
    takes two arrays of coordinates and creates a 2D hexbin plot and a violin plot (or
    just one of them)

    Parameters
    ----------
    abscissa, ordinate : arrays
        the coordinates of the data to plot
    bin_edges : array
        bin edges along the abscissa
    extent : 4-tuple of floats (default: None)
        extension of the abscissa, ordinate; given as is to plt.hexbin
    xlabel, ylabel : strings (defaults: "")
        labels for the two axes of either plot
    zlabel : string (default: "")
        label for the colorbar of the hexbin plot
    do_hex, do_violin : bools (defaults: True)
        whether or not to do the respective plots
    cm : colour map (default: plt.cm.inferno)
        colour map to be used for the hexbin plot
    kwargs : args dictionary
        more arguments to be passed to plt.hexbin
    """

    if axis:
        if do_hex and do_violin:
            from matplotlib.axes import Axes
            from matplotlib.transforms import Bbox
            axis_bbox = axis.get_position()
            axis.axis("off")
        else:
            plt.sca(axis)

    # make a normal 2D hexplot from the given data
    if do_hex:

        # if we do both plot types,
        if do_violin:
            if axis:
                ax_hex_pos = axis_bbox.get_points().copy(
                )  # [[x0, y0], [x1, y1]]
                ax_hex_pos[0, 1] += np.diff(ax_hex_pos,
                                            axis=0)[0, 1] * (.5 + v_padding)
                ax_hex = Axes(plt.gcf(), Bbox.from_extents(ax_hex_pos))
                plt.gcf().add_axes(ax_hex)
                plt.sca(ax_hex)
                ax_hex.set_xticklabels([])
            else:
                plt.subplot(211)

        plt.hexbin(abscissa,
                   ordinate,
                   gridsize=40,
                   extent=extent,
                   cmap=cm,
                   **kwargs)
        cb = plt.colorbar()
        cb.set_label(zlabel)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        if extent:
            plt.xlim(extent[:2])
            plt.ylim(extent[2:])

    # prepare and draw the data for the violin plot
    if do_violin:

        # if we do both plot types, open a subplot
        if do_hex:
            if axis:
                ax_vio_pos = axis_bbox.get_points().copy(
                )  # [[x0, y0], [x1, y1]]
                ax_vio_pos[1, 1] -= np.diff(ax_vio_pos,
                                            axis=0)[0, 1] * (.5 + v_padding)
                ax_vio = Axes(plt.gcf(), Bbox.from_extents(ax_vio_pos))
                plt.gcf().add_axes(ax_vio)
                plt.sca(ax_vio)
            else:
                plt.subplot(212)

        # to plot the violins, sort the ordinate values into a dictionary
        # the keys are the central values of the bins given by `bin_edges`
        val_vs_dep = {}
        bin_centres = (bin_edges[1:] + bin_edges[:-1]) / 2.

        for dep, val in zip(abscissa, ordinate):
            # get the bin number this event belongs into
            # outliers are put into the first and last bin accordingly
            ibin = np.clip(
                np.digitize(dep, bin_edges) - 1, 0,
                len(bin_centres) - 1)

            # the central value of the bin is the key for the dictionary
            if bin_centres[ibin] not in val_vs_dep:
                val_vs_dep[bin_centres[ibin]] = [val]
            else:
                val_vs_dep[bin_centres[ibin]] += [val]

        keys = [k[0] for k in sorted(val_vs_dep.items())]
        vals = [k[1] for k in sorted(val_vs_dep.items())]

        # calculate the widths of the violins as 90 % of the corresponding bin width
        widths = []
        for cen, wid in zip(bin_centres, (bin_edges[1:] - bin_edges[:-1])):
            if cen in keys:
                widths.append(wid * .9)

        plt.violinplot(vals,
                       keys,
                       points=60,
                       widths=widths,
                       showextrema=False,
                       showmedians=True)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)

        if extent:
            # adding a colour bar to the hexbin plot reduces its width by 1/5
            # adjusting the extent of the violin plot to sync up with the hexbin plot
            plt.xlim([
                extent[0],
                (5. * extent[1] - extent[0]) / 4. if do_hex else extent[1]
            ])
            # for good measure also sync the vertical extent
            plt.ylim(extent[2:])

        plt.grid()
Ejemplo n.º 21
0
    def draw(self):

        prefs = self.prefs
        dpi = self.ax_contain.figure.get_dpi()

        # Update palette
        palette = prefs.get('colors', {})
        if palette:
            self.palette.addPalette(palette)

        xlabel = prefs.get('xlabel', '')
        ylabel = prefs.get('ylabel', '')
        xticks_flag = prefs.get('xticks', True)
        yticks_flag = prefs.get('yticks', True)

        text_size = prefs['text_size']
        text_padding = prefs['text_padding']

        label_text_size = prefs.get('label_text_size', text_size)
        label_text_size_point = pixelToPoint(label_text_size, dpi)
        tick_text_size = prefs.get('tick_text_size', text_size)
        tick_text_size_point = pixelToPoint(tick_text_size, dpi)

        ytick_length = prefs.get('ytick_length', 7 * tick_text_size)

        plot_title = prefs.get('plot_title', '')
        if not plot_title or plot_title == 'NoTitle':
            plot_title_size = 0
            plot_title_padding = 0
        else:
            plot_title_size = prefs.get('plot_title_size', text_size)
            plot_title_padding = prefs.get('plot_text_padding', text_padding)
        plot_title_size_point = pixelToPoint(plot_title_size, dpi)

        stats_flag = prefs.get('statistics_line', False)
        stats_line = ''
        stats_line_space = 0.
        if stats_flag:
            stats_line = self.gdata.getStatString()
            stats_line_size = label_text_size
            stats_line_padding = label_text_size * 2.
            stats_line_space = stats_line_size + stats_line_padding

        plot_padding = prefs['plot_padding']
        plot_left_padding = prefs.get('plot_left_padding', plot_padding)
        plot_right_padding = prefs.get('plot_right_padding', 0)
        plot_bottom_padding = prefs.get('plot_bottom_padding', plot_padding)
        plot_top_padding = prefs.get('plot_top_padding', 0)
        frame_flag = prefs['frame']

        # Create plot axes, and set properties
        left, bottom, width, height = self.ax_contain.get_window_extent(
        ).bounds
        l, b, f_width, f_height = self.figure.get_window_extent().bounds

        # Space needed for labels and ticks
        x_label_space = 0
        if xticks_flag:
            x_label_space += tick_text_size * 1.5
        if xlabel:
            x_label_space += label_text_size * 1.5
        y_label_space = 0
        if yticks_flag:
            y_label_space += ytick_length
        if ylabel:
            y_label_space += label_text_size * 1.5

        ax_plot_rect = ( float( plot_left_padding + left + y_label_space ) / f_width,
                         float( plot_bottom_padding + bottom + x_label_space + stats_line_space ) / f_height,
                         float( width - plot_left_padding - plot_right_padding - y_label_space ) / f_width,
                         float( height - plot_bottom_padding - plot_top_padding - x_label_space - \
                                plot_title_size - 2 * plot_title_padding - stats_line_space ) / f_height )
        ax = Axes(self.figure, ax_plot_rect)
        if prefs['square_axis']:
            l, b, a_width, a_height = ax.get_window_extent().bounds
            delta = abs(a_height - a_width)
            if a_height > a_width:
                a_height = a_width
                ax_plot_rect = (
                    float(plot_left_padding + left) / f_width,
                    float(plot_bottom_padding + bottom + delta / 2.) /
                    f_height,
                    float(width - plot_left_padding - plot_right_padding) /
                    f_width,
                    float(height - plot_bottom_padding - plot_title_size -
                          2 * plot_title_padding - delta) / f_height)
            else:
                a_width = a_height
                ax_plot_rect = (
                    float(plot_left_padding + left + delta / 2.) / f_width,
                    float(plot_bottom_padding + bottom) / f_height,
                    float(width - plot_left_padding - delta) / f_width,
                    float(height - plot_bottom_padding - plot_title_size -
                          2 * plot_title_padding) / f_height)
            ax.set_position(ax_plot_rect)

        self.figure.add_axes(ax)
        self.ax = ax
        frame = ax.patch
        frame.set_fill(False)

        if frame_flag.lower() == 'off':
            self.ax.set_axis_off()
            self.log_xaxis = False
            self.log_yaxis = False
        else:
            # If requested, make x/y axis logarithmic
            if prefs.get('log_xaxis', 'False').find('r') >= 0:
                ax.semilogx()
                self.log_xaxis = True
            else:
                self.log_xaxis = False
            if prefs.get('log_yaxis', 'False').find('r') >= 0:
                ax.semilogy()
                self.log_yaxis = True
            else:
                self.log_yaxis = False

            if xticks_flag:
                setp(ax.get_xticklabels(), family=prefs['font_family'])
                setp(ax.get_xticklabels(), fontname=prefs['font'])
                setp(ax.get_xticklabels(), size=tick_text_size_point)
            else:
                setp(ax.get_xticklabels(), size=0)

            if yticks_flag:
                setp(ax.get_yticklabels(), family=prefs['font_family'])
                setp(ax.get_yticklabels(), fontname=prefs['font'])
                setp(ax.get_yticklabels(), size=tick_text_size_point)
            else:
                setp(ax.get_yticklabels(), size=0)

            setp(ax.get_xticklines(), markeredgewidth=pixelToPoint(0.5, dpi))
            setp(ax.get_xticklines(),
                 markersize=pixelToPoint(text_size / 2., dpi))
            setp(ax.get_yticklines(), markeredgewidth=pixelToPoint(0.5, dpi))
            setp(ax.get_yticklines(),
                 markersize=pixelToPoint(text_size / 2., dpi))
            setp(ax.get_xticklines(), zorder=4.0)

            line_width = prefs.get('line_width', 1.0)
            frame_line_width = prefs.get('frame_line_width', line_width)
            grid_line_width = prefs.get('grid_line_width', 0.1)
            plot_line_width = prefs.get('plot_line_width', 0.1)

            setp(ax.patch, linewidth=pixelToPoint(plot_line_width, dpi))
            #setp( ax.spines, linewidth=pixelToPoint(frame_line_width,dpi) )
            #setp( ax.axvline(), linewidth=pixelToPoint(1.0,dpi) )
            axis_grid_flag = prefs.get('plot_axis_grid', True)
            if axis_grid_flag:
                ax.grid(True,
                        color='#555555',
                        linewidth=pixelToPoint(grid_line_width, dpi))

            plot_axis_flag = prefs.get('plot_axis', True)
            if plot_axis_flag:
                # Set labels
                if xlabel:
                    t = ax.set_xlabel(xlabel)
                    t.set_family(prefs['font_family'])
                    t.set_fontname(prefs['font'])
                    t.set_size(label_text_size)

                if ylabel:
                    t = ax.set_ylabel(ylabel)
                    t.set_family(prefs['font_family'])
                    t.set_fontname(prefs['font'])
                    t.set_size(label_text_size)
            else:
                self.ax.set_axis_off()

        # Create a plot title, if necessary
        if plot_title:
            self.ax.title = self.ax.text(
                0.5,
                1. + float(plot_title_padding) / height,
                plot_title,
                verticalalignment='bottom',
                horizontalalignment='center',
                size=pixelToPoint(plot_title_size, dpi),
                family=prefs['font_family'],
                fontname=prefs['font'])
            self.ax.title.set_transform(self.ax.transAxes)
            self.ax.title.set_family(prefs['font_family'])
            self.ax.title.set_fontname(prefs['font'])
        if stats_line:
            self.ax.stats = self.ax.text(0.5, (-stats_line_space) / height,
                                         stats_line,
                                         verticalalignment='top',
                                         horizontalalignment='center',
                                         size=pixelToPoint(
                                             stats_line_size, dpi))

            self.ax.stats.set_transform(self.ax.transAxes)
Ejemplo n.º 22
0
def timeseriesPlot(category_list, **kwargs):
    """
    Supported arguments (via \**kwargs):

    :param curve_XXX: colon-separated curve info: (module_instance,[subtable],expr,title)
    :param filter: include only rows where specified column in result set matches value, can be specified more than once: col,value
    :param filter_XXX: include only rows where specified column in result set matches value for curve XXX, can be specified more than once: col,value
    :param exclude: include only rows where specified column in result set matches value, can be specified more than once: col,value
    :param exclude_XXX: include only rows where specified column in result set matches value for curve XXX, can be specified more than once: col,value
    :param legend: Show legend in image
    :param title: (string) Display a title above plot
    :param ylabel: self-explanatory
    :param start_date: Start date (Y-m-d)
    :param end_date: End date (Y-m-d)
    :param start_time: Start time (H:M)
    :param end_date: End time (H:M)
    :param renormalize: (true, false / 1, 0) Scales all curves to a [0,1] interval
    """
    from matplotlib.axes import Axes
    from matplotlib.figure import Figure
    from matplotlib.dates import AutoDateFormatter, AutoDateLocator, date2num
    import matplotlib.pyplot as plt
    logger = logging.getLogger(__name__ + ".timeseriesPlot")

    # generate plot
    fig = plt.figure()
    ax = Axes(fig, [.12, .15, .84, 0.78])
    fig.add_axes(ax)

    # extract constraints from kwargs dictionary
    constraint = {'filter': {}, 'exclude': {}}
    for t in constraint.iterkeys():
        for key, value in kwargs.iteritems():
            if key.startswith(t):
                if len(key) <= len(t) + 1:
                    curve = None
                else:
                    curve = key[len(t) + 1:]
                if type(value) is not list:
                    value = [
                        value,
                    ]
                for constr in value:
                    if curve not in constraint[t]:
                        constraint[t][curve] = []
                    constraint[t][curve].append(constr.split(','))
    errors = []
    try:
        # STAGE 1
        logger.debug("TEST")
        dat = getTimeseriesPlotConfig(**kwargs)
        logger.debug(
            "config: %s", "\n".join(
                map(lambda x: str(x[0]) + ": " + str(x[1]), dat.iteritems())))
        curve_dict = dat["curve_dict"]
        data_sources = dat["data_sources"]
        title = dat["title"]
        legend = dat["legend"]
        ylabel = dat["ylabel"]
        timerange = dat["timerange"]
        renormalize = dat["renormalize"]
        auth_required = dat["auth_required"]
        timerange = dat["timerange"]
        errors.extend(dat["errors"])

        # STAGE 3
        # Calculate the data structures for each curve
        vardict_name = "__internal_column_value_dict__"
        regexp_dollarvar = re.compile(r"\$([_a-zA-Z0-9]+)")
        for curve_name, (title, table, module_instance, expr,
                         table_name) in curve_dict.iteritems():
            query = __timeseriesTableQuery(curve_name, table, module_instance,
                                           constraint, timerange)
            try:
                result = query.execute()
                try:
                    column_index = dict(
                        (col, i) for i, col in enumerate(result.keys()))
                except TypeError:  # backward compatibility
                    column_index = dict(
                        (col, i) for i, col in enumerate(result.keys))

                source_data = result.fetchall()
            except Exception, e:
                logger.warning("Retrieving plot data:\n" +
                               traceback.format_exc())
                errors.append("Data '%s': %s" % (key, str(e)))
                continue
            try:
                num_rows = len(source_data)
                if num_rows == 0:
                    logger.debug("no data downloaded for curve")
                    curve_dict[curve_name] = (title, [], [])
                    continue

                logger.debug("Entries in sources: %i" % num_rows)
                dates = np.zeros(num_rows)
                data_points = np.zeros(num_rows)
                min_val = max_val = None

                use_matheval = False
                math_expr = expr
                # does the expression not match a column name?
                # Replace $varnames by a dict call to create valid math expression.
                if expr not in column_index:
                    use_matheval = True
                    math_expr = regexp_dollarvar.sub(vardict_name + "['\\1']",
                                                     expr)
                    logger.debug("Math expression " + repr(math_expr))

                for i, row in enumerate(source_data):
                    variables = dict(
                        (col, row[i]) for col, i in column_index.iteritems())
                    dates[i] = date2num(row[0])

                    if use_matheval:
                        val = hf.utility.matheval(math_expr,
                                                  {vardict_name: variables})
                    else:
                        val = variables[expr]

                    data_points[i] = val
                    if min_val is None:
                        min_val = val
                    elif min_val > val:
                        min_val = val
                    if max_val is None:
                        max_val = val
                    elif max_val < val:
                        max_val = val

                if renormalize and max_val - min_val != 0:
                    data_points = (data_points - min_val) / (max_val - min_val)
                elif renormalize:
                    data_points = np.zeros(len(data_points)) + 0.5

                curve_dict[curve_name] = (title, dates, data_points)
            except Exception, e:
                curve_dict[curve_name] = (title, [], [])
                logger.warning("Retrieving plot data:\n" +
                               traceback.format_exc())
                errors.append("Data '%s': %s" % (key, str(e)))
Ejemplo n.º 23
0
        bingFile.split('/')[-1])
f.write("** Produced by %s\n" % sys.argv[0].split('/')[-1])
f.write("** Perpendicular distances [m]: %s\n" %
        ', '.join(str(k) for k in list(distances.keys())))
f.write("** Parellel distances [m]: %s\n" %
        ', '.join(str(k) for k in list(distances.values())))
f.write("** Resolution regular background grid: %dm\n" % bg_resolution)
for coord in zip(grid_x, grid_y):
    f.write("RE disccart %0.1f %0.1f\n" % (coord[0], coord[1]))
f.close()
print("AERMOD receptor definition written to %s" % outputFile)

print("Plot roads and grid points")

fig = Figure(figsize=[14, 14])
ax = Axes(fig, [.1, .1, .8, .8])

# Add coordinates as lines to the plot
for i in range(len(knew)):
    #for i in range(10):
    (line1_xs, line1_ys) = zip(*knew[i])
    #(line1_xs, line1_ys) = knew[i]

    fig.add_axes(ax)
    ax.add_line(Line2D(line1_xs, line1_ys, linewidth=2, color='k'))
    ax.set_xlim(temp_xmin, temp_xmax)
    ax.set_ylim(temp_ymin, temp_ymax)

# Plot road following points in red
ax.scatter(road_x, road_y, color='red', s=3)
Ejemplo n.º 24
0
    def draw(self):

        prefs = self.prefs
        dpi = self.ax_contain.figure.get_dpi()

        # Update palette
        palette = prefs.get("colors", {})
        if palette:
            self.palette.addPalette(palette)

        xlabel = prefs.get("xlabel", "")
        ylabel = prefs.get("ylabel", "")
        xticks_flag = prefs.get("xticks", True)
        yticks_flag = prefs.get("yticks", True)

        text_size = prefs["text_size"]
        text_padding = prefs["text_padding"]

        label_text_size = prefs.get("label_text_size", text_size)
        label_text_size_point = pixelToPoint(label_text_size, dpi)
        tick_text_size = prefs.get("tick_text_size", text_size)
        tick_text_size_point = pixelToPoint(tick_text_size, dpi)

        ytick_length = prefs.get("ytick_length", 7 * tick_text_size)

        plot_title = prefs.get("plot_title", "")
        if not plot_title or plot_title == "NoTitle":
            plot_title_size = 0
            plot_title_padding = 0
        else:
            plot_title_size = prefs.get("plot_title_size", text_size)
            plot_title_padding = prefs.get("plot_text_padding", text_padding)
        plot_title_size_point = pixelToPoint(plot_title_size, dpi)

        stats_flag = prefs.get("statistics_line", False)
        stats_line = ""
        stats_line_space = 0.0
        if stats_flag:
            stats_line = self.gdata.getStatString()
            stats_line_size = label_text_size
            stats_line_padding = label_text_size * 2.0
            stats_line_space = stats_line_size + stats_line_padding

        plot_padding = prefs["plot_padding"]
        plot_left_padding = prefs.get("plot_left_padding", plot_padding)
        plot_right_padding = prefs.get("plot_right_padding", 0)
        plot_bottom_padding = prefs.get("plot_bottom_padding", plot_padding)
        plot_top_padding = prefs.get("plot_top_padding", 0)
        frame_flag = prefs["frame"]

        # Create plot axes, and set properties
        left, bottom, width, height = self.ax_contain.get_window_extent(
        ).bounds
        l, b, f_width, f_height = self.figure.get_window_extent().bounds

        # Space needed for labels and ticks
        x_label_space = 0
        if xticks_flag:
            x_label_space += tick_text_size * 1.5
        if xlabel:
            x_label_space += label_text_size * 1.5
        y_label_space = 0
        if yticks_flag:
            y_label_space += ytick_length
        if ylabel:
            y_label_space += label_text_size * 1.5

        ax_plot_rect = (
            float(plot_left_padding + left + y_label_space) / f_width,
            float(plot_bottom_padding + bottom + x_label_space +
                  stats_line_space) / f_height,
            float(width - plot_left_padding - plot_right_padding -
                  y_label_space) / f_width,
            float(height - plot_bottom_padding - plot_top_padding -
                  x_label_space - plot_title_size - 2 * plot_title_padding -
                  stats_line_space) / f_height,
        )
        ax = Axes(self.figure, ax_plot_rect)
        if prefs["square_axis"]:
            l, b, a_width, a_height = ax.get_window_extent().bounds
            delta = abs(a_height - a_width)
            if a_height > a_width:
                a_height = a_width
                ax_plot_rect = (
                    float(plot_left_padding + left) / f_width,
                    float(plot_bottom_padding + bottom + delta / 2.0) /
                    f_height,
                    float(width - plot_left_padding - plot_right_padding) /
                    f_width,
                    float(height - plot_bottom_padding - plot_title_size -
                          2 * plot_title_padding - delta) / f_height,
                )
            else:
                a_width = a_height
                ax_plot_rect = (
                    float(plot_left_padding + left + delta / 2.0) / f_width,
                    float(plot_bottom_padding + bottom) / f_height,
                    float(width - plot_left_padding - delta) / f_width,
                    float(height - plot_bottom_padding - plot_title_size -
                          2 * plot_title_padding) / f_height,
                )
            ax.set_position(ax_plot_rect)

        self.figure.add_axes(ax)
        self.ax = ax
        frame = ax.patch
        frame.set_fill(False)

        if frame_flag.lower() == "off":
            self.ax.set_axis_off()
            self.log_xaxis = False
            self.log_yaxis = False
        else:
            # If requested, make x/y axis logarithmic
            if prefs.get("log_xaxis", "False").find("r") >= 0:
                ax.semilogx()
                self.log_xaxis = True
            else:
                self.log_xaxis = False
            if prefs.get("log_yaxis", "False").find("r") >= 0:
                ax.semilogy()
                self.log_yaxis = True
            else:
                self.log_yaxis = False

            if xticks_flag:
                setp(ax.get_xticklabels(), family=prefs["font_family"])
                setp(ax.get_xticklabels(), fontname=prefs["font"])
                setp(ax.get_xticklabels(), size=tick_text_size_point)
            else:
                setp(ax.get_xticklabels(), size=0)

            if yticks_flag:
                setp(ax.get_yticklabels(), family=prefs["font_family"])
                setp(ax.get_yticklabels(), fontname=prefs["font"])
                setp(ax.get_yticklabels(), size=tick_text_size_point)
            else:
                setp(ax.get_yticklabels(), size=0)

            setp(ax.get_xticklines(), markeredgewidth=pixelToPoint(0.5, dpi))
            setp(ax.get_xticklines(),
                 markersize=pixelToPoint(text_size / 2.0, dpi))
            setp(ax.get_yticklines(), markeredgewidth=pixelToPoint(0.5, dpi))
            setp(ax.get_yticklines(),
                 markersize=pixelToPoint(text_size / 2.0, dpi))
            setp(ax.get_xticklines(), zorder=4.0)

            line_width = prefs.get("line_width", 1.0)
            frame_line_width = prefs.get("frame_line_width", line_width)
            grid_line_width = prefs.get("grid_line_width", 0.1)
            plot_line_width = prefs.get("plot_line_width", 0.1)

            setp(ax.patch, linewidth=pixelToPoint(plot_line_width, dpi))
            # setp( ax.spines, linewidth=pixelToPoint(frame_line_width,dpi) )
            # setp( ax.axvline(), linewidth=pixelToPoint(1.0,dpi) )
            axis_grid_flag = prefs.get("plot_axis_grid", True)
            if axis_grid_flag:
                ax.grid(True,
                        color="#555555",
                        linewidth=pixelToPoint(grid_line_width, dpi))

            plot_axis_flag = prefs.get("plot_axis", True)
            if plot_axis_flag:
                # Set labels
                if xlabel:
                    t = ax.set_xlabel(xlabel)
                    t.set_fontname(prefs["font"])
                    t.set_fontsize(label_text_size)

                if ylabel:
                    t = ax.set_ylabel(ylabel)
                    t.set_fontname(prefs["font"])
                    t.set_fontsize(label_text_size)
            else:
                self.ax.set_axis_off()

        # Create a plot title, if necessary
        if plot_title:
            self.ax.title = self.ax.text(
                0.5,
                1.0 + float(plot_title_padding) / height,
                plot_title,
                verticalalignment="bottom",
                horizontalalignment="center",
                size=pixelToPoint(plot_title_size, dpi),
                family=prefs["font_family"],
                fontname=prefs["font"],
            )
            self.ax.title.set_transform(self.ax.transAxes)
            self.ax.title.set_fontname(prefs["font"])
        if stats_line:
            self.ax.stats = self.ax.text(
                0.5,
                (-stats_line_space) / height,
                stats_line,
                verticalalignment="top",
                horizontalalignment="center",
                size=pixelToPoint(stats_line_size, dpi),
            )

            self.ax.stats.set_transform(self.ax.transAxes)
Ejemplo n.º 25
0
    def create_panel(self):
        """ Initializes the matplotlib figure and empty axes according to projector calibration.

        The figure can be accessed by its attribute. It will be 'deactivated' to prevent random apperance in notebooks.
        """
        pn.extension(raw_css=[self.css])
        # Create a panel object and serve it within an external bokeh browser that will be opened in a separate window

        # In this special case, a "tight" layout would actually add again white space to the plt canvas,
        # which was already cropped by specifying limits to the axis

        self.figure = Figure(figsize=(self.p_frame_width / self.dpi, self.p_frame_height / self.dpi),
                             dpi=self.dpi)
        self.ax = Axes(self.figure, [0., 0., 1., 1.])
        self.figure.add_axes(self.ax)
        self.ax.set_axis_off()
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)

        self.frame = pn.pane.Matplotlib(self.figure,
                                        width=self.p_frame_width,
                                        height=self.p_frame_height,
                                        margin=[self.p_frame_top, 0, 0, self.p_frame_left],
                                        tight=False,
                                        dpi=self.dpi,
                                        css_classes=['frame']
                                        )
        plt.close(self.figure)  # close figure to prevent inline display

        if self.enable_colorbar:
            self.create_colorbar()

        if self.enable_legend:
            self.create_legend()

        if self.enable_hot:
            self.create_hot()

        if self.enable_profile:
            self.create_profile()

        # Combine panel and deploy bokeh server
        if self.pos_colorbar == "vertical":
            self.sidebar = pn.Column(self.colorbar, self.legend, self.hot, self.profile,
                                     margin=[self.p_frame_top, 0, 0, 0],
                                     )

            self.panel = pn.Row(pn.Column(self.frame, None),
                                self.sidebar,
                                width=self.p_width,
                                height=self.p_height,
                                sizing_mode='fixed',
                                css_classes=['panel']
                                )
        elif self.pos_colorbar == "horizontal":
            self.sidebar = pn.Column(self.legend, self.hot, self.profile,
                                     margin=[self.p_frame_top, 0, 0, 0],
                                     )
            self.panel = pn.Row(pn.Column(self.frame, self.colorbar),
                                self.sidebar,
                                width=self.p_width,
                                height=self.p_height,
                                sizing_mode='fixed',
                                css_classes=['panel']
                                )
        else:
            raise AttributeError

        return True
Ejemplo n.º 26
0
    def _process(self, element, key=None):
        try:
            from matplotlib.contour import QuadContourSet
            from matplotlib.axes import Axes
            from matplotlib.figure import Figure
        except ImportError:
            raise ImportError("contours operation requires matplotlib.")
        extent = element.range(0) + element.range(1)[::-1]

        if type(element) is Raster:
            data = [np.flipud(element.data)]
        elif isinstance(element, Image):
            data = [np.flipud(element.dimension_values(2, flat=False))]
        elif isinstance(element, QuadMesh):
            data = (element.dimension_values(0, False, flat=False),
                    element.dimension_values(1, False, flat=False),
                    element.dimension_values(2, flat=False))

        xdim, ydim = element.dimensions('key', label=True)
        if self.p.filled:
            contour_type = Polygons
        else:
            contour_type = Contours
        vdims = element.vdims[:1]

        if isinstance(self.p.levels, int):
            levels = self.p.levels + 2 if self.p.filled else self.p.levels + 3
            zmin, zmax = element.range(2)
            levels = np.linspace(zmin, zmax, levels)
            if zmin == zmax:
                contours = contour_type([], [xdim, ydim], vdims)
                return (element * contours) if self.p.overlaid else contours
        else:
            levels = self.p.levels

        fig = Figure()
        ax = Axes(fig, [0, 0, 1, 1])
        contour_set = QuadContourSet(ax,
                                     *data,
                                     filled=self.p.filled,
                                     extent=extent,
                                     levels=levels)

        paths = []
        empty = np.full((1, 2), np.NaN)
        for level, cset in zip(contour_set.get_array(),
                               contour_set.collections):
            subpaths = []
            for path in cset.get_paths():
                if path.codes is None:
                    subpaths.append(path.vertices)
                else:
                    subpaths += np.split(path.vertices,
                                         np.where(path.codes == 1)[0][1:])
            if len(subpaths):
                subpath = np.concatenate(
                    [p for sp in subpaths for p in (sp, empty)][:-1])
            else:
                subpath = np.array([])
            paths.append({(xdim, ydim): subpath, element.vdims[0].name: level})
        contours = contour_type(paths,
                                label=element.label,
                                kdims=element.kdims,
                                vdims=vdims)
        if self.p.overlaid:
            contours = element * contours
        return contours
    def _process(self, element, key=None):
        try:
            from matplotlib.contour import QuadContourSet
            from matplotlib.axes import Axes
            from matplotlib.figure import Figure
            from matplotlib.dates import num2date, date2num
        except ImportError:
            raise ImportError("contours operation requires matplotlib.")
        extent = element.range(0) + element.range(1)[::-1]

        xs = element.dimension_values(0, True, flat=False)
        ys = element.dimension_values(1, True, flat=False)
        zs = element.dimension_values(2, flat=False)

        # Ensure that coordinate arrays specify bin centers
        if xs.shape[0] != zs.shape[0]:
            xs = xs[:-1] + np.diff(xs, axis=0)/2.
        if xs.shape[1] != zs.shape[1]:
            xs = xs[:, :-1] + (np.diff(xs, axis=1)/2.)
        if ys.shape[0] != zs.shape[0]:
            ys = ys[:-1] + np.diff(ys, axis=0)/2.
        if ys.shape[1] != zs.shape[1]:
            ys = ys[:, :-1] + (np.diff(ys, axis=1)/2.)
        data = (xs, ys, zs)

        # if any data is a datetime, transform to matplotlib's numerical format
        data_is_datetime = tuple(isdatetime(arr) for k, arr in enumerate(data))
        if any(data_is_datetime):
            data = tuple(
                date2num(d) if is_datetime else d
                for d, is_datetime in zip(data, data_is_datetime)
            )

        xdim, ydim = element.dimensions('key', label=True)
        if self.p.filled:
            contour_type = Polygons
        else:
            contour_type = Contours
        vdims = element.vdims[:1]

        kwargs = {}
        levels = self.p.levels
        zmin, zmax = element.range(2)
        if isinstance(self.p.levels, int):
            if zmin == zmax:
                contours = contour_type([], [xdim, ydim], vdims)
                return (element * contours) if self.p.overlaid else contours
            data += (levels,)
        else:
            kwargs = {'levels': levels}

        fig = Figure()
        ax = Axes(fig, [0, 0, 1, 1])
        contour_set = QuadContourSet(ax, *data, filled=self.p.filled,
                                     extent=extent, **kwargs)
        levels = np.array(contour_set.get_array())
        crange = levels.min(), levels.max()
        if self.p.filled:
            levels = levels[:-1] + np.diff(levels)/2.
            vdims = [vdims[0].clone(range=crange)]

        paths = []
        empty = np.array([[np.nan, np.nan]])
        for level, cset in zip(levels, contour_set.collections):
            exteriors = []
            interiors = []
            for geom in cset.get_paths():
                interior = []
                polys = geom.to_polygons(closed_only=False)
                for ncp, cp in enumerate(polys):
                    if any(data_is_datetime[0:2]):
                        # transform x/y coordinates back to datetimes
                        xs, ys = np.split(cp, 2, axis=1)
                        if data_is_datetime[0]:
                            xs = np.array(num2date(xs))
                        if data_is_datetime[1]:
                            ys = np.array(num2date(ys))
                        cp = np.concatenate((xs, ys), axis=1)
                    if ncp == 0:
                        exteriors.append(cp)
                        exteriors.append(empty)
                    else:
                        interior.append(cp)
                if len(polys):
                    interiors.append(interior)
            if not exteriors:
                continue
            geom = {
                element.vdims[0].name:
                num2date(level) if data_is_datetime[2] else level,
                (xdim, ydim): np.concatenate(exteriors[:-1])
            }
            if self.p.filled and interiors:
                geom['holes'] = interiors
            paths.append(geom)
        contours = contour_type(paths, label=element.label, kdims=element.kdims, vdims=vdims)
        if self.p.overlaid:
            contours = element * contours
        return contours
Ejemplo n.º 28
0
            elif("".join( radar.sweep_mode['data'][0][0:3])).lower()\
                    in vpt_modes:
                sweep_type = 'vpt'
        else:
            #strings
            if radar.sweep_mode['data'][0].lower() in ppi_modes:
                sweep_type = 'ppi'
            elif radar.sweep_mode['data'][0].lower() in rhi_modes:
                sweep_type = 'rhi'
            elif radar.sweep_mode['data'][0].lower() in vpt_modes:
                sweep_type = 'vpt'

    except:
        sweep_type = 'ppi'
    fig = plt.figure(figsize=[1, 0.73])
    ax = Axes(plt.gcf(), [0, 0, 1, 1], yticks=[], xticks=[], frame_on=False)
    #Create radar display

    radar_display = pyart.graph.RadarDisplay(radar)
    #Plot
    if sweep_type == 'ppi':
        plt.gcf().delaxes(plt.gca())
        plt.gcf().add_axes(ax)
        radar_display.plot_ppi(primary_measurement,
                               0,
                               vmin=pvmin,
                               vmax=pvmax,
                               mask_outside=False,
                               title_flag=False,
                               axislabels_flag=False,
                               colorbar_flag=False,