Ejemplo n.º 1
0
    def __init__(self):
        self.widgets = gtk.glade.XML('mpl_with_glade.glade')
        self.widgets.signal_autoconnect(GladeHandlers.__dict__)

        self.figure = Figure(figsize=(8, 6), dpi=72)
        self.axis = Subplot(self.figure, 111)
        self.figure.add_axis(self.axis)
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axis.plot(t, s)
        self.axis.set_xlabel('time (s)')
        self.axis.set_ylabel('voltage')

        self.canvas = FigureCanvasGTK(self.figure)  # a gtk.DrawingArea
        self.canvas.show()
        self['vboxMain'].pack_start(self.canvas, gtk.TRUE, gtk.TRUE)
        self['vboxMain'].show()

        # below is optional if you want the navigation toolbar
        self.navToolbar = NavigationToolbar(self.canvas, self['windowMain'])
        self.navToolbar.lastDir = '/var/tmp/'
        self['vboxMain'].pack_start(self.navToolbar)
        self.navToolbar.show()

        sep = gtk.HSeparator()
        sep.show()
        self['vboxMain'].pack_start(sep, gtk.TRUE, gtk.TRUE)

        self['vboxMain'].reorder_child(self['buttonClickMe'], -1)
Ejemplo n.º 2
0
    def __init__(self, fig=None, *args, **kwargs):
        """
Accepts the same keywords as a standard subplot, plus a specific `series` keyword.

:Parameters:
    `fig` : Figure
        Base figure.

:Keywords:
    `series` : TimeSeries
        Data to plot

        """
        # Retrieve the series ...................
        _series = kwargs.pop('series',None)
        Subplot.__init__(self,fig,*args,**kwargs)
#        # Force fig to be defined .....
#        if fig is None:
#            fig = TSFigure(_series)
        # Process options .......................
        if _series is not None:
            assert hasattr(_series, "dates")
            self._series = _series.ravel()
            self.xdata = _series.dates
            self.freq = _series.dates.freq
            self.xaxis.set_major_locator

        else:
            self._series = None
            self.xdata = None
            self.freq = None
        self._austoscale = False
        # Get the data to plot
        self.legendsymbols = []
        self.legendlabels = []
Ejemplo n.º 3
0
    def __init__(self, fig=None, *args, **kwargs):

        # Retrieve the series ...................
        _series = kwargs.pop('series', getattr(fig, 'series', None))
        Subplot.__init__(self, fig, *args, **kwargs)

        # Process options .......................
        if _series is not None:
            assert hasattr(_series, "dates")
            self._series = _series.ravel()
            self.xdata = self._series.dates
            # TODO: Mmh, what's going on with the line below ?
            self.xaxis.set_major_locator
        else:
            self._series = None
            self.xdata = None
        self._austoscale = False
        # Get the data to plot
        self.legendsymbols = []
        self.legendlabels = []
        # keep track of axis format and tick info
        self.date_axis_info = None
        # used to keep track of current view interval to determine if we need
        # to reset date_axis_info
        self.view_interval = None
Ejemplo n.º 4
0
def draw_dna_connections(dna_helix_graph: nx.DiGraph,
                         nucleotide_plots: Dict[Nucleotide, _NUCLEOTIDE_PLOT],
                         subplot: plt_axes.Subplot,
                         verbosity: int = 0):
    """
    Draw dna connections on given subplot according to verbosity level

    Parameters
    ----------
    dna_helix_graph
        directed graph with nucleotides as nodes
    nucleotide_plots
        mapping of nucleotide to its plot
    subplot
        subplot to draw on
    verbosity
        verbosity of the visualization;
        if verbosity == 0, then only the connections between
        nucleotide are drawn, otherwise connections between nucleotide keys
        are drawn
    """
    nucleotide_positions = {
        each_nucleotide: each_nucleotide_plot.body.center
        for each_nucleotide, each_nucleotide_plot in nucleotide_plots.items()}
    _draw_dna_connections(
        subplot, dna_helix_graph, nucleotide_positions, nucleotide_plots,
        verbosity=verbosity)
    subplot.add_callback(
        partial(_draw_dna_connections,
                dna_helix_graph=dna_helix_graph,
                nucleotide_positions=nucleotide_positions,
                nucleotide_plots=nucleotide_plots, verbosity=verbosity))
Ejemplo n.º 5
0
    def __init__(self, fig=None, *args, **kwargs):

        # Retrieve the series ...................
        _series = kwargs.pop("series", getattr(fig, "series", None))
        Subplot.__init__(self, fig, *args, **kwargs)

        # Process options .......................
        if _series is not None:
            assert hasattr(_series, "dates")
            self._series = _series.ravel()
            self.xdata = self._series.dates
            # TODO: Mmh, what's going on with the line below ?
            self.xaxis.set_major_locator
        else:
            self._series = None
            self.xdata = None
        self._austoscale = False
        # Get the data to plot
        self.legendsymbols = []
        self.legendlabels = []
        # keep track of axis format and tick info
        self.date_axis_info = None
        # used to keep track of current view interval to determine if we need
        # to reset date_axis_info
        self.view_interval = None
Ejemplo n.º 6
0
def _draw_nucleotide_info(event, dna_helix_graph: nx.DiGraph,
                          text_object: plt.Text, subplot: plt_axes.Subplot):
    mouseevent = event.mouseevent
    if mouseevent.dblclick or mouseevent.button != 1:
        return

    nucleotide_name = event.artist.get_label().split(":")[-1]
    nucleotide = _get_nucleotide_by_name(nucleotide_name, dna_helix_graph)
    nucleotide_info = nucleotide_utils.get_nucleotide_info(
        nucleotide=nucleotide)

    nucleotide_info_text = "Information for {}:\n\n".format(
        nucleotide_name).upper()
    nucleotide_info_text += nucleotide_utils.format_nucleotide_info(
        nucleotide_info)

    xlim = subplot.get_xlim()
    ylim = subplot.get_ylim()
    text_coord = (xlim[1] - 0.05 * (xlim[1] - xlim[0]),
                  ylim[1] - 0.05 * (ylim[1] - ylim[0]))

    text_object.set_text(nucleotide_info_text)
    text_object.set_x(text_coord[0])
    text_object.set_y(text_coord[1])
    text_object.set_visible(True)
    plt.show()
Ejemplo n.º 7
0
 def legend(self, **kwargs):
     """
 Adds a legend to the plot.
     """
     if not hasattr(self, 'barlist'):
         args = (('Global', 'Cold', 'Neutral', 'Warm'),)
     else:
         args = (self.barlist, ('Global', 'Cold', 'Neutral', 'Warm'),)
     Subplot.legend(self, *args, **kwargs)
Ejemplo n.º 8
0
    def tsplot(self,*parms,**kwargs):
        """Plots the data parsed in argument.
This command accepts the same keywords as `matplotlib.plot`."""
#        parms = tuple(list(parms) + kwargs.pop('series',None))
#        print "Parameters: %s - %i" % (parms, len(parms))
#        print "OPtions: %s - %i" % (kwargs, len(kwargs))
        parms = self._check_plot_params(*parms)
        self.legendlabels.append(kwargs.get('label',None))
        Subplot.plot(self, *parms,**kwargs)
        self.format_dateaxis()
Ejemplo n.º 9
0
def _draw_legend(subplot: plt_axes.Subplot):
    nucleotide_patches, nucleotide_class_names_with_names = (
        subplot.figure.gca().get_legend_handles_labels())
    nucleotide_class_names = [
        each_class_name_with_name.split(":")[0]
        for each_class_name_with_name in nucleotide_class_names_with_names]
    legend_labels, legend_items = zip(*OrderedDict(
        zip(nucleotide_class_names, nucleotide_patches)).items())
    subplot.legend(legend_items, legend_labels, loc="lower right",
                   bbox_to_anchor=(0, 0), title="Nucleotide types")
Ejemplo n.º 10
0
def compressed_image():
    img = Image.open('compressed_image.jpg')
    fig = plt.figure()
    ax = Subplot(fig, 111)
    ax.imshow(img, cmap="gray")
    fig.add_subplot(ax)

    output = io.BytesIO()
    FigureCanvas(fig).print_jpg(output)
    return Response(output.getvalue(), mimetype='image/jpg')
Ejemplo n.º 11
0
def plot_chem_shift_dist(title,residues, amino_acids):
    three_lets = [aa.three_let for aa in amino_acids]
    nuclei = ['CO', 'CA', 'CB', 'CG', 'CG1', 'CG2',
              'CD', 'CD1', 'CD2', 'CE', 'CE1', 'CE2',
              'CE3', 'CZ', 'CZ2', 'CZ3', 'CH2']
    colors = ['b','g','r','c','c','c',
              'm','m','m','y','y','y',
              'y','gray','gray','gray','k']
    
    means, stds = data_array(amino_acids, nuclei)
    fig = pl.figure()
    ax = Subplot(fig,111)
    ax = pl.gca()
    fig.add_subplot(ax)
    
    x = means
#    print nan_to_num(x)
    y = ones(x.shape)
    for i in range(0,x.shape[0]):
        y[i]*=i
        
    for j in range(0,x.shape[1]):
        ax.errorbar(x.T[j], y.T[j], xerr=nan_to_num(stds.T[j]), 
                    linestyle='None',marker='o', color=colors[j], 
                    label=(nuclei[j]), linewidth=4, capsize=20)
    
    for r in residues:
        x = ones_like(means)*nan
        name = r.name
        shifts, atoms = r.get_carbons(previous=False)
        for shift,atom in zip(shifts,atoms):
            if atom in nuclei:
                j = nuclei.index(atom)
#                if name != "NAA":
#                    name = one2Three(r.name[0])
                i = three_lets.index(name)
                x[i][j] = shift
        for j in range(0,x.shape[1]):
            ax.plot(x.T[j],y.T[j], marker="x",linestyle="None", color=colors[j],markersize=15)
    
    pl.yticks(arange(0,20), three_lets)
    pl.ylim(-1,20)
    pl.title('Verteilung chemischer Verschiebungen\n %s'%title)
    pl.ylabel('Aminosaeure')
    pl.xlabel('ppm')
    pl.rcParams.update({'font.size': 22})
    # Shink current axis by 20%
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    
    # Put a legend to the right of the current axis
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    pl.show()
Ejemplo n.º 12
0
 def legend(self, **kwargs):
     """
 Adds a legend to the plot.
     """
     if not hasattr(self, 'barlist'):
         args = (('Global', 'Cold', 'Neutral', 'Warm'), )
     else:
         args = (
             self.barlist,
             ('Global', 'Cold', 'Neutral', 'Warm'),
         )
     Subplot.legend(self, *args, **kwargs)
Ejemplo n.º 13
0
    def __init__(self, fig=None, *args, **kwargs):
        """Initializes instance.
        
    Parameters
    ----------
    fig : {None, figure instance}
        Figure from which the plot will depend.
        If None, the current figure is selected.
    series : ClimateSeries
        Series to convert.
    freq : {var}, optional
        A valid frequency specifier (as a string or integer), or a 3-letter 
        string corresponding to the first quarter of the year.
        Use this parameter if the series does not have an adequate frequency.
    func : {None,function}, optional
        Function controlling how data sharing the same new dates should be
        manipulated.
        This function should handle masked values appropriately.
    kwargs : dictionary
        Dictionary of optional parameters.
        The same parameters as for a standard subplot instantiation are recognized.

    See Also
    --------
    scikits.hydroclimpy.periodize
        Function to convert a series into a 2D series with years as rows and
        periods as columns.
        """
        # Initialize the plot ..............
        fig = fig or kwargs.pop('fig', None)
        if fig is None:
            fig = pyplot.gcf()
        elif not isinstance(fig, Figure):
            fig = pyplot.figure(fig)
        if len(args) == 0:
            args = (111,)
        # Get the information about the series
        if not hasattr(series, 'ensoindices'):
            errmsg = "ENSO indices should be defined for the input series!"
            raise AttributeError(errmsg)
        series = kwargs.pop('series', None)
        freq = kwargs.pop('freq', None)
        func = kwargs.pop('func', None)
        self.series = periodize(series, freq=freq, func=func)
        self.cold = self.series.cold
        self.neutral = self.series.neutral
        self.warm = self.series.warm
        self.freq = check_freq(self.series._dates.freq)
        self.positions = np.arange(self.series.shape[-1])
        self.periodlabels = self.series.optinfo['period_names']
        Subplot.__init__(self, fig, *args, **kwargs)
Ejemplo n.º 14
0
    def __init__(self, fig=None, *args, **kwargs):
        """Initializes instance.
        
    Parameters
    ----------
    fig : {None, figure instance}
        Figure from which the plot will depend.
        If None, the current figure is selected.
    series : ClimateSeries
        Series to convert.
    freq : {var}, optional
        A valid frequency specifier (as a string or integer), or a 3-letter 
        string corresponding to the first quarter of the year.
        Use this parameter if the series does not have an adequate frequency.
    func : {None,function}, optional
        Function controlling how data sharing the same new dates should be
        manipulated.
        This function should handle masked values appropriately.
    kwargs : dictionary
        Dictionary of optional parameters.
        The same parameters as for a standard subplot instantiation are recognized.

    See Also
    --------
    scikits.hydroclimpy.periodize
        Function to convert a series into a 2D series with years as rows and
        periods as columns.
        """
        # Initialize the plot ..............
        fig = fig or kwargs.pop('fig', None)
        if fig is None:
            fig = pyplot.gcf()
        elif not isinstance(fig, Figure):
            fig = pyplot.figure(fig)
        if len(args) == 0:
            args = (111, )
        # Get the information about the series
        if not hasattr(series, 'ensoindices'):
            errmsg = "ENSO indices should be defined for the input series!"
            raise AttributeError(errmsg)
        series = kwargs.pop('series', None)
        freq = kwargs.pop('freq', None)
        func = kwargs.pop('func', None)
        self.series = periodize(series, freq=freq, func=func)
        self.cold = self.series.cold
        self.neutral = self.series.neutral
        self.warm = self.series.warm
        self.freq = check_freq(self.series._dates.freq)
        self.positions = np.arange(self.series.shape[-1])
        self.periodlabels = self.series.optinfo['period_names']
        Subplot.__init__(self, fig, *args, **kwargs)
Ejemplo n.º 15
0
 def setup_plot(self, figure, name, xlabel, ylabel):
     plot = Subplot(figure, 111, axisbg='white', frameon='False')
     #plot.set_axis_bg_color('#000000')
     plot.set_title(name)
     plot.set_xlabel(xlabel)
     plot.set_ylabel(ylabel)
     return plot
Ejemplo n.º 16
0
    def __init__(self):
        self.widgets = gtk.glade.XML('mpl_with_glade.glade')
        self.widgets.signal_autoconnect(GladeHandlers.__dict__)

        self.figure = Figure(figsize=(8,6), dpi=72)
        self.axis = Subplot(self.figure, 111)
        self.figure.add_axis(self.axis)
        t = arange(0.0,3.0,0.01)
        s = sin(2*pi*t)
        self.axis.plot(t,s)
        self.axis.set_xlabel('time (s)')
        self.axis.set_ylabel('voltage')

        self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea
        self.canvas.show()
        self['vboxMain'].pack_start(self.canvas, gtk.TRUE, gtk.TRUE)
        self['vboxMain'].show()
        
        # below is optional if you want the navigation toolbar
        self.navToolbar = NavigationToolbar(self.canvas, self['windowMain'])
        self.navToolbar.lastDir = '/var/tmp/'
        self['vboxMain'].pack_start(self.navToolbar)
        self.navToolbar.show()

        sep = gtk.HSeparator()
        sep.show()
        self['vboxMain'].pack_start(sep, gtk.TRUE, gtk.TRUE)


        self['vboxMain'].reorder_child(self['buttonClickMe'],-1)
Ejemplo n.º 17
0
def _draw_click_instructions(subplot: plt_axes.Subplot,
                             doubleclick=True, singleclck=True):
    instruction_texts = list()
    instruction_texts.append("Interactive instructions:")
    if singleclck:
        instruction_texts.append(
            "Click once on nucleotide to see its information")
    if doubleclick:
        instruction_texts.append(
            "Make double clock on nucleotide to cut the subgraph with its "
            "incoming and outgoing nucleotides in new figure")

    instruction_text = "\n".join(instruction_texts)
    subplot.annotate(
        instruction_text, (0.5, 0.01), xycoords="figure fraction",
        ha="center", va="bottom", ma="left",
        bbox=dict(facecolor='white', edgecolor='blue', pad=5.0))
Ejemplo n.º 18
0
    def __init__(self, find_source, parent, *args, **kwargs):
        Subplot.__init__(self, parent.figure, *args, **kwargs)
        self.signals = {}
        self.parent = parent
        self.paused = False
        self.autoscale = True
        self.static = False

        self.find_source = find_source
        
        self.set_title_action = QtGui.QAction("Set plot title", parent)
        self.adjust_axes_action = QtGui.QAction("Adjust plot axes", parent)
        self.adjust_signals_action = QtGui.QAction("Change signals plotted", parent)

        link(self.set_title_action.triggered, self.adjust_title)
        link(self.adjust_axes_action.triggered, self.adjust_axes)
        link(self.adjust_signals_action.triggered, self.adjust_signals)
Ejemplo n.º 19
0
    def __init__(self, fig=None, *args, **kwargs):

        # Retrieve the series ...................
        _series = kwargs.pop('series', getattr(fig, 'series', None))
        Subplot.__init__(self, fig, *args, **kwargs)

        # Process options .......................
        self.set_series(series=_series)

        self._austoscale = False
        # Get the data to plot
        self.legendsymbols = []
        self.legendlabels = []
        # keep track of axis format and tick info
        self.date_axis_info = None
        # used to keep track of current view interval to determine if we need
        # to reset date_axis_info
        self.view_interval = None
Ejemplo n.º 20
0
    def tsplot(self, *args, **kwargs):
        """
    Plots the data parsed in argument to the current axes.
    This command accepts the same optional keywords as :func:`matplotlib.pyplot.plot`.

    The argument ``args`` is a variable length argument, allowing for multiple
    data to be plotted at once. Acceptable combinations are:

    No arguments or a format string:
       The time series associated with the subplot is plotted with the given
       format.
       If no format string is given, the default format is used instead.
       For example, to plot the underlying time series with the default format,
       use:

          >>> tsplot()

       To plot the underlying time series with a red solid line, use the command:

          >>> tsplot('r-')

    a :class:`~scikits.timeseries.TimeSeries` object or one of its subclass
    with or without a format string:
       The given time series is plotted with the given format.
       If no format string is given, the default format is used instead.

    an array or sequence, with or without a format string:
       The data is plotted with the given format
       using the :attr:`~TimeSeriesPlot.xdata` attribute of the plot as abscissae.

    two arrays or sequences, with or without a format string:
       The data are plotted with the given format, using the first array as
       abscissae and the second as ordinates.


    Parameters
    ----------
    args : var
        Sequence of arguments, as described previously.
    kwargs : var
        Optional parameters.
        The same parameters are accepted as for :meth:`matplotlib.axes.Subplot.plot`.

        """
        args = self._check_plot_params(*args)
        self.legendlabels.append(kwargs.get('label', None))
        plotted = Subplot.plot(self, *args, **kwargs)
        self.format_dateaxis()

        # when adding a right axis (using add_yaxis), for some reason the
        # x axis limits don't get properly set. This gets around the problem
        xlim = self.get_xlim()
        if xlim[0] == 0.0 and xlim[1] == 1.0:
            # if xlim still at default values, autoscale the axis
            self.autoscale_view()
        self.reset_datelimits()
        return plotted
Ejemplo n.º 21
0
    def tsplot(self, *args, **kwargs):
        """
    Plots the data parsed in argument to the current axes.
    This command accepts the same optional keywords as :func:`matplotlib.pyplot.plot`.

    The argument ``args`` is a variable length argument, allowing for multiple
    data to be plotted at once. Acceptable combinations are:

    No arguments or a format string:
       The time series associated with the subplot is plotted with the given
       format.
       If no format string is given, the default format is used instead.
       For example, to plot the underlying time series with the default format,
       use:

          >>> tsplot()

       To plot the underlying time series with a red solid line, use the command:

          >>> tsplot('r-')

    a :class:`~scikits.timeseries.TimeSeries` object or one of its subclass
    with or without a format string:
       The given time series is plotted with the given format.
       If no format string is given, the default format is used instead.

    an array or sequence, with or without a format string:
       The data is plotted with the given format
       using the :attr:`~TimeSeriesPlot.xdata` attribute of the plot as abscissae.

    two arrays or sequences, with or without a format string:
       The data are plotted with the given format, using the first array as
       abscissae and the second as ordinates.


    Parameters
    ----------
    args : var
        Sequence of arguments, as described previously.
    kwargs : var
        Optional parameters.
        The same parameters are accepted as for :meth:`matplotlib.axes.Subplot.plot`.

        """
        args = self._check_plot_params(*args)
        self.legendlabels.append(kwargs.get("label", None))
        plotted = Subplot.plot(self, *args, **kwargs)
        self.format_dateaxis()

        # when adding a right axis (using add_yaxis), for some reason the
        # x axis limits don't get properly set. This gets around the problem
        xlim = self.get_xlim()
        if xlim[0] == 0.0 and xlim[1] == 1.0:
            # if xlim still at default values, autoscale the axis
            self.autoscale_view()
        self.reset_datelimits()
        return plotted
Ejemplo n.º 22
0
def _draw_nucleotide_body(nucleotide, center, subplot: plt_axes.Subplot,
                          radius=10.0):
    nucleotide_color, nucleotide_base_class = _get_nucleotide_color(nucleotide)
    nucleotide_name = nucleotide.name
    if len(nucleotide_name) > 10:
        nucleotide_name = nucleotide_name.replace("_", "_\n")

    nucleotide_body = patches.Circle(
        center, radius=radius, color=nucleotide_color)
    text_object = subplot.text(
        center[0], center[1], nucleotide_name, va="center", ha="center")
    text_object.draw(subplot.figure.canvas.renderer)
    subplot.add_patch(nucleotide_body)
    nucleotide_body.add_callback(
        partial(_nucleotide_name_callback, text_object=text_object))
    nucleotide_body.set_label(":".join([nucleotide_base_class.__name__,
                                        nucleotide.name]))
    nucleotide_body.set_picker(True)
    return nucleotide_body
Ejemplo n.º 23
0
    def topics(self, axis: Subplot) -> BarContainer:
        """Plot the relative importance of the individual topics.

        Parameters
        ----------
        axis: Subplot
            The matplotlib axis to plot into.

        Returns
        -------
        BarContainer
            The container for the bars plotted into the given axis.

        """
        colors = [f'C{color}' for color in self.__topic_range]
        axis.set(xlabel='Topic', ylabel='Importance')
        axis.set_title('Topic distribution')
        return axis.bar(self.__topic_range, self.__topics, color=colors,
                        tick_label=self.__topic_range)
Ejemplo n.º 24
0
    def convergence(self, axis: Subplot) -> List[Line2D]:
        """Plot the convergence of the PLSA run.

        The quantity to be minimized is the Kullback-Leibler divergence
        between the original document-word matrix and its approximation
        given by the (conditional) PLSA factorization.

        Parameters
        ----------
        axis: Subplot
            The matplotlib axis to plot into.

        Returns
        -------
        list of Line2D
            The line object plotted into the given axis.

        """
        axis.set(xlabel='Iteration', ylabel='Kullback-Leibler divergence')
        return axis.plot(self.__convergence)
Ejemplo n.º 25
0
    def topics_in_doc(self, i_doc: int, axis: Subplot) -> BarContainer:
        """Plot the relative weights of topics in a given document.

        Parameters
        ----------
        i_doc: int
            Index of the document to plot. Numbering starts at 0.
        axis: Subplot
            The matplotlib axis to plot into.

        Returns
        -------
        BarContainer
            The container for the bars plotted into the given axis.

        """
        colors = [f'C{color}' for color in self.__topic_range]
        axis.set(xlabel='Topic', ylabel='Importance', title=f'Document {i_doc}')
        return axis.bar(self.__topic_range, self.__topic_given_doc[i_doc],
                        color=colors, tick_label=self.__topic_range)
Ejemplo n.º 26
0
    def words_in_topic(self, i_topic: int, axis: Subplot) -> AxesImage:
        """Plot the relative importance of words in a given topic.

        Parameters
        ----------
        i_topic: int
            Index of the topic to plot. Numbering starts at 0.
        axis: Subplot
            The matplotlib axis to plot into.

        Returns
        -------
        AxesImage
            The image with the produced word cloud.

        """
        word_given_topic = dict(self.__word_given_topic[i_topic])
        wordcloud = self.__wordcloud.generate_from_frequencies(word_given_topic)
        axis.set_title(f'Topic {i_topic}')
        axis.set_axis_off()
        return axis.imshow(wordcloud, interpolation='bilinear')
Ejemplo n.º 27
0
def _add_update_events(subplot: plt_axes.Subplot, dna_helix_graph: nx.DiGraph,
                       nucleotide_plots: Dict[Nucleotide, _NUCLEOTIDE_PLOT]):
    subplot.figure.canvas.mpl_connect(
        'draw_event', lambda x: subplot.pchanged())
    subplot.figure.canvas.mpl_connect(
        'resize_event', lambda x: subplot.pchanged())

    text_initial_position = list(nucleotide_plots.values())[0].body.center
    text_object = subplot.text(
        text_initial_position[0], text_initial_position[1], "",
        ha="right", va="top", ma="left",
        bbox=dict(facecolor='white', edgecolor='blue', pad=5.0))
    text_object.set_visible(False)

    subplot.figure.canvas.mpl_connect(
        'button_press_event',
        partial(_remove_nucleotide_info_text, text_object=text_object))
    subplot.figure.canvas.mpl_connect(
        'pick_event',
        partial(_draw_nucleotide_info, dna_helix_graph=dna_helix_graph,
                text_object=text_object, subplot=subplot))
Ejemplo n.º 28
0
def _draw_nucleotide_keys(keys_required: Optional[List[str]],
                          keys_optional: Optional[List[str]],
                          center: Sequence[float],
                          nucleotide_body_patch: patches.Circle,
                          subplot: plt_axes.Subplot,
                          color, radius=10.0, width=5.0,
                          theta_min=0, theta_max=180):
    # pylint: disable=too-many-arguments
    # not possible to have less arguments without more complexity
    # pylint: disable=too-many-locals
    # is not possible to split the method without more complexity
    keys_required = keys_required or []
    keys_optional = keys_optional or []

    keys_all = keys_required + keys_optional

    if not keys_all:
        return None

    number_of_keys = len(keys_all)
    theta_delta = (theta_max - theta_min) / number_of_keys
    thetas = np.arange(theta_min, theta_max, theta_delta)
    key_patches = {}
    for each_key, each_start_theta in zip(keys_all, thetas):
        hatch = "x" if each_key in keys_optional else None
        theta1 = each_start_theta
        theta2 = theta1 + theta_delta
        key_patch = patches.Wedge(
            center, radius + width, theta1, theta2, width=width,
            facecolor=color, hatch=hatch, edgecolor="white")
        key_patches[each_key] = key_patch

        text_object = _draw_key_text(
            each_key, center, theta1, theta2, radius, width, subplot)
        key_patch.add_callback(partial(
            _nucleotide_key_text_callback,
            text_object=text_object,
            nucleotide_body_patch=nucleotide_body_patch))
        subplot.add_patch(key_patch)
    return key_patches
Ejemplo n.º 29
0
    def prediction(self, doc: str, axis: Subplot) -> BarContainer:
        """Plot the predicted relative weights of topics in a new document.

        Parameters
        ----------
        doc: str
            A new document given as a single string.
        axis: Subplot
            The matplotlib axis to plot into.

        Returns
        -------
        BarContainer
            The container for the bars plotted into the given axis.

        """
        colors = [f'C{color}' for color in self.__topic_range]
        prediction, n_unknown_words, _ = self.__predict(doc)
        axis.set(xlabel='Topic', ylabel='Importance')
        axis.set_title(f'Number of unknown words: {n_unknown_words}')
        return axis.bar(self.__topic_range, prediction, color=colors,
                        tick_label=self.__topic_range)
Ejemplo n.º 30
0
def _draw_key_text(text: str, center, theta1, theta2, radius, width,
                   subplot: plt_axes.Subplot, **text_kwargs):
    text_center, theta = _get_wedge_center_and_angle(
        center, radius, theta1, theta2, width)
    text_angle = theta - 90
    if text_angle > 90:
        text_angle = text_angle - 180
    if len(text) > 10:
        text = text.replace("_", "_\n")
    text_object = subplot.annotate(text, xy=text_center,
                                   verticalalignment="center",
                                   horizontalalignment="center",
                                   rotation=text_angle, **text_kwargs)
    text_object.draw(subplot.figure.canvas.renderer)
    return text_object
Ejemplo n.º 31
0
def _modify_axis(
    ax: Subplot,
    time: list,
    data: list,
    *,
    color: str,
    label: str,
):
    ax.set_ylabel(label, color=color)
    if isinstance(time[0], list):
        for plot in zip(time, data):
            ax.plot(*plot)
    else:
        ax.plot(time, data, color=color)
    ax.tick_params(axis='y', labelcolor=color)

    ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=5))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
Ejemplo n.º 32
0
import matplotlib
matplotlib.use('GD')
from matplotlib.backends.backend_gd import Figure, show
from matplotlib.axes import Subplot

dpi = 100
figsize = (5, 5)
f = Figure(figsize, dpi)
a = Subplot(f, 111)
f.add_axis(a)
l = a.plot([1,2,3], [4,5,6])

a.set_xlabel('time (s)')
a.set_ylabel('Signal 2')
f.print_figure('gdtest', dpi)
show()

Ejemplo n.º 33
0
                    self.select_text(t)
                    return


win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

fig = Figure(figsize=(5, 4), dpi=100)

ax = Subplot(fig, 111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)

ax.plot(t, s)
ax.set_title("click on line or text")
fig.add_axis(ax)

canvas = PickerCanvas(fig)
canvas.show()
vbox.pack_start(canvas)

toolbar = NavigationToolbar(canvas, win)
toolbar.show()
vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)
Ejemplo n.º 34
0
    def __init__(self, *args, **kw):
        wx.Panel.__init__(self, *args, **kw)

        # Fig
        self.fig = Figure(
            figsize=(1, 1),
            dpi=75,
            facecolor='white',
            edgecolor='white',
        )
        # Canvas
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.fig.set_canvas(self.canvas)

        # Axes
        self.axes = self.fig.add_axes(Subplot(self.fig, 111))
        self.axes.set_autoscale_on(False)
        self.theta_axes = self.axes.twinx()
        self.theta_axes.set_autoscale_on(False)

        # Show toolbar or not?
        self.toolbar = NavigationToolbar2WxAgg(self.canvas)
        self.toolbar.Show(True)

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)

        # Panel layout
        self.profile_selector_label = wx.StaticText(self, label="Sample")
        self.profile_selector = wx.Choice(self)
        self.profile_selector.Hide()
        self.profile_selector_label.Hide()
        self.Bind(wx.EVT_CHOICE, self.OnProfileSelect)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas,
                       1,
                       border=2,
                       flag=wx.LEFT | wx.TOP | wx.GROW)
        self.tbsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.tbsizer.Add(self.toolbar, 0, wx.ALIGN_CENTER_VERTICAL)
        self.tbsizer.AddSpacer(20)
        self.tbsizer.Add(self.profile_selector_label, 0,
                         wx.ALIGN_CENTER_VERTICAL)
        self.tbsizer.AddSpacer(5)
        self.tbsizer.Add(self.profile_selector, 0, wx.ALIGN_CENTER_VERTICAL)
        self.sizer.Add(self.tbsizer)

        self.SetSizer(self.sizer)
        self.sizer.Fit(self)

        # Status bar
        frame = self.GetTopLevelParent()
        self.statusbar = frame.GetStatusBar()
        if self.statusbar is None:
            self.statusbar = frame.CreateStatusBar()
        status_update = lambda msg: self.statusbar.SetStatusText(msg)

        # Set the profile interactor
        self.profile = ProfileInteractor(self.axes,
                                         self.theta_axes,
                                         status_update=status_update)

        # Add context menu and keyboard support to canvas
        self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnContextMenu)
        #self.canvas.Bind(wx.EVT_LEFT_DOWN, lambda evt: self.canvas.SetFocus())

        self.model = None
        self._need_interactors = self._need_redraw = False
        self.Bind(wx.EVT_SHOW, self.OnShow)
Ejemplo n.º 35
0
 def __init__(self, fig, *args, **kwargs):
     Subplot.__init__(self,fig,*args,**kwargs)
     print "Hello, MultichannelSubplot here."
Ejemplo n.º 36
0
import matplotlib
matplotlib.use('GD')
from matplotlib.backends.backend_gd import Figure, show
from matplotlib.axes import Subplot

dpi = 100
figsize = (5, 5)
f = Figure(figsize, dpi)
a = Subplot(f, 111)
f.add_axis(a)
l = a.plot([1, 2, 3], [4, 5, 6])

a.set_xlabel('time (s)')
a.set_ylabel('Signal 2')
f.print_figure('gdtest', dpi)
show()
Ejemplo n.º 37
0
from matplotlib.axes import Subplot
from matplotlib.figure import Figure
import gtk

win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

fig = Figure(figsize=(5,4), dpi=100)
ax = Subplot(fig, 111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

ax.plot(t,s)
fig.add_axis(ax)

canvas = FigureCanvasGTK(fig)  # a gtk.DrawingArea
canvas.show()
vbox.pack_start(canvas)


toolbar = NavigationToolbar(canvas, win)
toolbar.show()
vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)
Ejemplo n.º 38
0
                    self.select_text(t)
                    return


win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

fig = Figure(figsize=(5, 4), dpi=100)

ax = Subplot(fig, 111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)

ax.plot(t, s)
ax.set_title('click on line or text')
fig.add_axis(ax)

canvas = PickerCanvas(fig)
canvas.show()
vbox.pack_start(canvas)

toolbar = NavigationToolbar(canvas, win)
toolbar.show()
vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)
Ejemplo n.º 39
0
 def __init__(self, fig, *args, **kwargs):
     Subplot.__init__(self, fig, *args, **kwargs)
     print "Hello, MultichannelSubplot here."
Ejemplo n.º 40
0
from matplotlib.backends.backend_gtk import FigureCanvasGTK
from matplotlib.figure import Figure

import gtk

win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

f = Figure(figsize=(5, 4), dpi=100)
a = Subplot(f, 111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)

a.plot(t, s)
f.add_axis(a)

canvas = FigureCanvasGTK(f)  # a gtk.DrawingArea
canvas.show()
vbox.pack_start(canvas)

button = gtk.Button('Quit')
button.connect('clicked', lambda b: gtk.mainquit())
button.show()
vbox.pack_start(button)
Ejemplo n.º 41
0
                    return
                

                            
win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

fig = Figure(figsize=(5,4), dpi=100)

ax = Subplot(fig, 111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

ax.plot(t,s)
ax.set_title('click on line or text')
fig.add_axis(ax)

canvas = PickerCanvas(fig)
canvas.show()
vbox.pack_start(canvas)

toolbar = NavigationToolbar(canvas, win)
toolbar.show()
vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)
Ejemplo n.º 42
0
from matplotlib.backends import Figure
from matplotlib.axes import Subplot
import Numeric as numpy
import gtk

win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

f = Figure(figsize=(5,4), dpi=100)
a = Subplot(f, 111)
t = numpy.arange(0.0,3.0,0.01)
s = numpy.sin(2*numpy.pi*t)

a.plot(t,s)
f.add_axis(a)
f.show()
vbox.pack_start(f)

button = gtk.Button('Quit')
button.connect('clicked', lambda b: gtk.mainquit())
button.show()
vbox.pack_start(button)

win.show()
gtk.mainloop()
Ejemplo n.º 43
0
from matplotlib.axes import Subplot
from matplotlib.figure import Figure
import gtk

win = gtk.Window()
win.set_name("Embedding in GTK")
win.connect("destroy", gtk.mainquit)
win.set_border_width(5)

vbox = gtk.VBox(spacing=3)
win.add(vbox)
vbox.show()

fig = Figure(figsize=(5,4), dpi=100)
ax = Subplot(fig, 111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

ax.plot(t,s)
fig.add_axis(ax)

canvas = FigureCanvasGTK(fig)  # a gtk.DrawingArea
canvas.show()
vbox.pack_start(canvas)


toolbar = NavigationToolbar(canvas, win)
toolbar.show()
vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)