Exemplo n.º 1
0
    def hide(self, part="all"):
        """

        .. py:method:: hide(self, part = "all")

        Hides the requested part of the grid plot.

        **Parameters**

            part
                a string with the following possible values:

                    "lower"
                        hides the lower triangle of the grid plot.

                    "upper"
                        hides the upper triangle of the grid plot.

                    "diag"
                        hides the diagonal of the grid plot.

                    "all"
                        hides all grid plots and the colorbar.

                    "cbar"
                        hides the colorbar of the grid plot.

                    The string can also be a mix of the above keywords, 
                    separated by the ``+`` sign or some other delimiter. 
                    For example, ``"lower+upper+cbar"``

        **Returns**

            None

        """

        allhidden = "all" in part
        if allhidden or ("upper" in part):
            self.currentFig.pairgrid.map_upper(hide_current_axis)
        if allhidden or ("lower" in part):
            self.currentFig.pairgrid.map_lower(hide_current_axis)
            colnames = dfutils.getColNamesIndex(self._dfref().columns,
                                                self.columns)[0]
            if not allhidden:
                for i in range(len(colnames)):
                    ax = self.currentFig.pairgrid.axes[:][i][i]
                    ax.set_xlabel(colnames[i])
                    ax.set_ylabel(colnames[i])
                    ax.xaxis.set_tick_params(which="both", labelbottom=True)
                    ax.yaxis.set_tick_params(which="both", labelbottom=True)
        if allhidden or ("diag" in part):
            self.currentFig.pairgrid.map_diag(hide_current_axis)
        if allhidden or ("cbar" in part): self.currentFig.figure.cbar.remove()
Exemplo n.º 2
0
    def show(self, part="all"):
        """

        .. py:method:: show(self, part = "all")

        Shows the requested part of the grid plot.

            **Parameters**

                part
                    a string with the following possible values:

                        "lower"
                            shows the lower triangle of the grid plot.

                        "upper"
                            shows the lower triangle of the grid plot.

                        "diag"
                            shows the diagonal of the grid plot.

                        "all"
                            shows all grid plots.

                        "cbar"
                            shows the colorbar of the grid plot.

                        The string can also be a mix of the above keywords, 
                        separated by the ``+`` sign or some other delimiter. 
                        For example, ``"lower+upper+cbar"``

            **Returns**

                None

        """

        allshown = "all" in part
        if allshown or ("upper" in part):
            self.currentFig.pairgrid.map_upper(show_current_axis)
        if allshown or ("lower" in part):
            self.currentFig.pairgrid.map_lower(show_current_axis)
            colnames = dfutils.getColNamesIndex(self._dfref().columns,
                                                self.columns)[0]
            colnamesLength = len(colnames)
            for i in range(colnamesLength):
                ax = self.currentFig.pairgrid.axes[:][i][i]
                if colnamesLength - 1 > i > 0:
                    ax.set_xlabel("")
                    ax.set_ylabel("")
                    ax.xaxis.set_tick_params(which="both", labelbottom=False)
                    ax.yaxis.set_tick_params(which="both", labelbottom=False)
                elif i == 0:
                    ax.xaxis.set_tick_params(which="both", labelbottom=False)
                    ax.set_xlabel("")
                else:
                    ax.yaxis.set_tick_params(which="both", labelbottom=False)
                    ax.set_ylabel("")
        if allshown or ("diag" in part):
            self.currentFig.pairgrid.map_diag(show_current_axis)
        if allshown or ("cbar" in part): self._addcbar()
Exemplo n.º 3
0
    def plot(self):
        """

        .. py:method:: plot(self)

        Generate a grid plot from the selected columns of the object's dataframe.

            **Parameters**

                None

            **Returns**

                None. However, this method causes side-effects by manipulating 
                the existing attributes of the object.

        """

        # setup figure

        scatterplotEnabled = self.scatterplot_kws is not None
        lineplotEnabled = self.lineplot_kws is not None
        distplotEnabled = self.distplot_kws is not None
        kdeplotEnabled = (self.kdeplot_kws is not None) and (self.kdecorner
                                                             is not None)
        lsplotEnabled = (scatterplotEnabled
                         or lineplotEnabled) and (self.lscorner is not None)

        if self.set_kws == (): self.set_kws = {}

        kdeUpperEnabled = False
        kdeLowerEnabled = False
        if kdeplotEnabled:
            if self.kdecorner == "auto":
                kdeLowerEnabled = True
            elif isinstance(self.kdecorner, str):
                if "upper" in self.kdecorner: kdeUpperEnabled = True
                if "lower" in self.kdecorner: kdeLowerEnabled = True
            else:
                raise Exception(
                    "The input argument 'kdecorner' must be either,\n\n" +
                    "    'upper', 'lower', 'upper-lower', 'auto',\n\n" +
                    "or otherwise None.")

        lsUpperEnabled = False
        lsLowerEnabled = False
        if lsplotEnabled:
            if self.lscorner == "auto":
                lsUpperEnabled = not kdeUpperEnabled
                lsLowerEnabled = not kdeLowerEnabled
                lsplotEnabled = lsLowerEnabled or lsUpperEnabled
            elif isinstance(self.lscorner, str):
                if "upper" in self.lscorner: lsUpperEnabled = True
                if "lower" in self.lscorner:
                    lsLowerEnabled = True
                    if self.kdecorner == "auto":
                        kdeUpperEnabled = not lsUpperEnabled
                        kdeLowerEnabled = not lsLowerEnabled
                        kdeplotEnabled = kdeLowerEnabled or kdeUpperEnabled
            else:
                raise Exception(
                    "The input argument 'lscorner' must be either,\n\n" +
                    "    'upper', 'lower', 'upper-lower', 'auto',\n\n" +
                    "or otherwise None.")
        elif kdeplotEnabled:
            if self.kdecorner == "auto":
                kdeUpperEnabled = True
                kdeLowerEnabled = True

        if self.kdeplot_kws == (): self.kdeplot_kws = {}
        if isinstance(self.kdeplot_kws, dict):
            #self.kdeplot_kws["cbar"]=True if lsplotEnabled==False else False
            self.kdeplot_kws["cbar"] = False
            if "cmap" not in self.kdeplot_kws.keys():
                self.kdeplot_kws["cmap"] = "Blues"
            if "alpha" not in self.kdeplot_kws.keys():
                self.kdeplot_kws["alpha"] = 1
            if "shade" not in self.kdeplot_kws.keys():
                self.kdeplot_kws["shade"] = True
            if "n_levels" not in self.kdeplot_kws.keys():
                self.kdeplot_kws["n_levels"] = 100
            if "shade_lowest" not in self.kdeplot_kws.keys():
                self.kdeplot_kws["shade_lowest"] = True
        elif kdeplotEnabled:
            raise Exception(
                "The input argument 'kdeplot_kws' must be None or a dictionary,\n"
                +
                "each (key,value) pair of which represents an (attribute,value)\n"
                + "of seaborn library's kdeplot() function.")

        if self.distplot_kws == (): self.distplot_kws = {}
        if isinstance(self.distplot_kws, dict):
            if "kde" not in self.distplot_kws.keys():
                self.distplot_kws["kde"] = False
            if "hist_kws" not in self.distplot_kws.keys():
                self.distplot_kws["hist_kws"] = {
                    "histtype": "stepfilled",
                    "linewidth": 1
                }
        elif distplotEnabled:
            raise Exception(
                "The input argument 'distplot_kws' must be None or a dictionary,\n"
                +
                "each (key,value) pair of which represents an (attribute,value)\n"
                + "of seaborn library's distplot() function.")

        if self.lineplot_kws == (): self.lineplot_kws = {}
        if isinstance(self.lineplot_kws, dict):
            self.lineplot_kws["figure_kws"] = None
            if "legend_kws" not in self.lineplot_kws.keys():
                self.lineplot_kws["legend_kws"] = None
            if "colorbar_kws" not in self.lineplot_kws.keys():
                self.lineplot_kws["colorbar_kws"] = None
            if "lc_kws" not in self.lineplot_kws.keys():
                self.lineplot_kws["lc_kws"] = {"cmap": "winter"}
            if "set_kws" not in self.lineplot_kws.keys():
                self.lineplot_kws["set_kws"] = self.set_kws
            if "ccolumns" not in self.lineplot_kws.keys():
                if scatterplotEnabled:
                    self.lineplot_kws["ccolumns"] = None
                else:
                    self.lineplot_kws["ccolumns"] = ()
            if self.lineplot_kws["ccolumns"] is None:
                if scatterplotEnabled:
                    if "plot_kws" in self.lineplot_kws.keys():
                        if "color" not in self.lineplot_kws["plot_kws"].keys():
                            self.lineplot_kws["plot_kws"]["color"] = "grey"
                        if "alpha" not in self.lineplot_kws["plot_kws"].keys():
                            self.lineplot_kws["plot_kws"]["alpha"] = 0.3
                    else:
                        self.lineplot_kws["plot_kws"] = {
                            "color": "grey",
                            "alpha": 0.3
                        }
            else:
                if "plot_kws" not in self.lineplot_kws.keys():
                    self.lineplot_kws["plot_kws"] = None
        elif lineplotEnabled:
            raise Exception(
                "The input argument 'lineplot_kws' must be None or a dictionary,\n"
                +
                "each (key,value) pair of which represents an (attribute,value)\n"
                + "of ParaMonte library's LinePlot() class.")

        if self.scatterplot_kws == (): self.scatterplot_kws = {}
        if isinstance(self.scatterplot_kws, dict):
            self.scatterplot_kws["figure_kws"] = None
            if "legend_kws" not in self.scatterplot_kws.keys():
                self.scatterplot_kws["legend_kws"] = None
            if "colorbar_kws" not in self.scatterplot_kws.keys():
                self.scatterplot_kws["colorbar_kws"] = None
            if "set_kws" not in self.scatterplot_kws.keys():
                self.scatterplot_kws["set_kws"] = self.set_kws
            if "scatter_kws" in self.scatterplot_kws.keys():
                if "s" not in self.scatterplot_kws["scatter_kws"].keys():
                    self.scatterplot_kws["scatter_kws"]["s"] = 3
                if "cmap" not in self.scatterplot_kws["scatter_kws"].keys():
                    self.scatterplot_kws["scatter_kws"]["cmap"] = "winter"
                if "alpha" not in self.scatterplot_kws["scatter_kws"].keys():
                    self.scatterplot_kws["scatter_kws"]["alpha"] = 1
                if "zorder" not in self.scatterplot_kws["scatter_kws"].keys():
                    self.scatterplot_kws["scatter_kws"]["zorder"] = 4
            else:
                self.scatterplot_kws["scatter_kws"] = {
                    "s": 3,
                    "cmap": "winter",
                    "alpha": 1,
                    "zorder": 4
                }
        elif scatterplotEnabled:
            raise Exception(
                "The input argument 'scatterplot_kws' must be None or a dictionary,\n"
                +
                "each (key,value) pair of which represents an (attribute,value)\n"
                + "of ParaMonte library's ScatterPlot() class.")

        if self.colorbar_kws == (): self.colorbar_kws = {}

        #########################
        if self._isdryrun: return
        #########################

        # check rows presence

        if self.rows is None:
            rowindex = range(len(self._dfref().index))
        else:
            rowindex = self.rows

        # check columns presence

        colnames, colindex = dfutils.getColNamesIndex(self._dfref().columns,
                                                      self.columns)

        # make pairgrid plot

        import seaborn as _sns
        from matplotlib import pyplot as _plt

        self.currentFig = ParaMonteFigure()
        if self.set_kws is not None: _sns.set(**self.set_kws)
        self.currentFig.pairgrid = _sns.PairGrid(
            self._dfref()[colnames].iloc[rowindex, :])
        self.currentFig.figure = self.currentFig.pairgrid.fig

        # hide axes as requested

        if (lsUpperEnabled or kdeUpperEnabled):
            self._upperEnabled = True
        else:
            self.hide("upper")
            self._upperEnabled = False

        if (lsLowerEnabled or kdeLowerEnabled):
            self._lowerEnabled = True
        else:
            self.hide("lower")
            self._lowerEnabled = False

        if distplotEnabled:
            self._diagEnabled = True
        else:
            self._diagEnabled = False
            self.hide("diag")

        # adjust subplot interspaces

        self.currentFig.pairgrid.fig.tight_layout()
        self.currentFig.pairgrid.fig.subplots_adjust(hspace=0.05, wspace=0.05)

        # set up figure layout if needed

        # check data type

        noDataPassed = ""
        if self._dfref is None:
            noDataPassed = "It appears that no data has been passed for plotting.\n"
        elif not isinstance(self._dfref, _wref.ref):
            noDataPassed = "It appears that you have messed with the\ninternal representation of data in the object.\n"
        elif not isinstance(self._dfref(), _pd.DataFrame):
            noDataPassed = "The input data is not a pandas' dataframe.\n"
        if noDataPassed:
            raise Exception(
                noDataPassed +
                "The input data must be a pandas' dataframe.\n" +
                "Please pass a dataFrame to the constructor or at\n" +
                "the time of calling the object (which is callable with\n" +
                "the same input arguments as the object's constructor.")

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

        # define currentFig components

        nrow = len(self.currentFig.pairgrid.axes[:])
        nlsplotStr = str(
            (lsUpperEnabled + lsLowerEnabled) * nrow * (nrow - 1) // 2)
        nkdeplotStr = str(
            (kdeUpperEnabled + kdeLowerEnabled) * nrow * (nrow - 1) // 2)

        self.currentFig.targetList = [[[] for j in range(nrow)]
                                      for i in range(nrow)]
        #self.currentFig.kdeplotList     = [ [ [] for j in range(nrow) ] for i in range(nrow) ]
        self.currentFig.lineplotList = [[[] for j in range(nrow)]
                                        for i in range(nrow)]
        self.currentFig.scatterplotList = [[[] for j in range(nrow)]
                                           for i in range(nrow)]
        #self.currentFig.distplotList    = [ [] for i in range(nrow) ]

        #####################################
        #### add distplots as needed
        #####################################

        if distplotEnabled:
            self._timer.tic(
                msg="adding the diagonal histograms (distplots)... ", end=_eol)
            self.currentFig.pairgrid.map_diag(_sns.distplot,
                                              **self.distplot_kws)
            self._timer.toc()

#        if distplotEnabled:
#
#            msg.note( msg = "adding the diagonal histograms (distplots)...", methodName = self._methodName )
#
#            counter = 0
#            for irow, row in enumerate(self.currentFig.pairgrid.axes[:]):
#
#                counter += 1
#                self._timer.tic( msg = "    " + str(counter) + " out of " + nlsplotStr + ": " + colnames[irow] + " - " + colnames[irow] + "... ", end = _eol )
#
#                ax = row[irow]
#                _plt.sca(ax)
#
#                currentXlim = ax.get_xlim()
#                currentYlim = ax.get_ylim()
#
#                self.currentFig.distplotList[irow] = HistPlot   ( dataFrame = self._dfref()
#                                                                , columns = colnames[irow]
#                                                                , rows = self.rows
#                                                                , figure_kws = None
#                                                                , legend_kws = None
#                                                                , set_kws = self.set_kws
#                                                                , distplot_kws = self.distplot_kws
#                                                                )
#                self.currentFig.distplotList[irow].plot()
#
#                if self._lowerEnabled:
#                    ax.set_xlabel("")
#                    ax.set_ylabel("")
#
#                ax.set_xlim(currentXlim)
#                ax.set_ylim(currentYlim)
#
#                self._timer.toc()
#
#            _plt.tight_layout()

#####################################
#### add line/scatter plots as needed
#####################################

        if lsplotEnabled:

            msg.note(msg="adding the line/scatter plots...",
                     methodName=self._methodName)

            counter = 0
            for irow, row in enumerate(self.currentFig.pairgrid.axes[:]):

                for icol, ax in enumerate(row):

                    self.currentFig.targetList[irow][icol] = Target(axes=ax)

                    if (icol > irow
                            and lsUpperEnabled) or (icol < irow
                                                    and lsLowerEnabled):

                        counter += 1
                        self._timer.tic(msg="    " + str(counter) +
                                        " out of " + nlsplotStr + ": " +
                                        colnames[icol] + " - " +
                                        colnames[irow] + "... ",
                                        end=_eol)

                        _plt.sca(ax)
                        #_sns.set( self.set_kws )

                        if lineplotEnabled:

                            self.currentFig.lineplotList[irow][
                                icol] = LinePlot(dataFrame=self._dfref(),
                                                 xcolumns=colnames[icol],
                                                 ycolumns=colnames[irow],
                                                 rows=self.rows,
                                                 **self.lineplot_kws)
                            self.currentFig.lineplotList[irow][icol].plot()

                        if scatterplotEnabled:

                            self.currentFig.scatterplotList[irow][
                                icol] = ScatterPlot(dataFrame=self._dfref(),
                                                    xcolumns=colnames[icol],
                                                    ycolumns=colnames[irow],
                                                    rows=self.rows,
                                                    **self.scatterplot_kws)
                            self.currentFig.scatterplotList[irow][icol].plot()

                        #ax.get_xaxis().set_visible(False)
                        #ax.get_yaxis().set_visible(False)
                        #if irow < nrow-1: ax.set_xlabel("")
                        #if icol > 0: ax.set_ylabel("")
                        #ax.set_xlim(currentXlim)
                        #ax.set_ylim(currentYlim)

                        self._timer.toc()

            _plt.tight_layout()

        #####################################
        #### add kdeplots plots as needed
        #####################################

        if kdeplotEnabled:
            msg.note(
                msg=
                "adding kdeplots... depending on the number of plots, this may take a long while.",
                methodName=self._methodName)
            if kdeUpperEnabled:
                self._timer.tic(
                    msg="    adding the upper-triangle kdeplots...", end=_eol)
                self.currentFig.pairgrid.map_upper(_sns.kdeplot,
                                                   **self.kdeplot_kws)
                self._timer.toc()
            if kdeLowerEnabled:
                self._timer.tic(
                    msg="    adding the lower-triangle kdeplots...", end=_eol)
                self.currentFig.pairgrid.map_lower(_sns.kdeplot,
                                                   **self.kdeplot_kws)
                self._timer.toc()

        if self.outputFile is not None:
            self.currentFig.figure.savefig(self.outputFile,
                                           bbox_inches='tight',
                                           pad_inches=0.0)

        # set the ticks and labels

        nrowMinusOne = nrow - 1
        from matplotlib.pyplot import setp
        for irow, row in enumerate(self.currentFig.pairgrid.axes[:]):
            for icol, ax in enumerate(row):
                if self._lowerEnabled:
                    if icol > 0:
                        ax.set_ylabel("")
                    if irow < nrowMinusOne:
                        ax.set_xlabel("")
                elif self._upperEnabled:
                    if (not kdeplotEnabled):
                        if icol != irow:
                            ax.set_ylabel("")
                            ax.set_xlabel("")
                        if icol == irow:
                            ax.set_xlabel(colnames[irow])
                            ax.set_ylabel(colnames[icol])
                            ax.xaxis.set_tick_params(which="both",
                                                     labelbottom=True)
                            ax.yaxis.set_tick_params(which="both",
                                                     labelbottom=True)
                    elif icol > irow:
                        ax.set_ylabel("")
                        ax.set_xlabel("")

        import matplotlib.pyplot as _plt
        _plt.subplots_adjust(hspace=0.15, wspace=0.15)

        # add colorbar

        self._addcbar()
Exemplo n.º 4
0
    def get(self, reself: tp.Optional[bool] = False, **kwargs):
        """

        Compute the autocorrelations of the selected columns 
        of the input dataframe to the object's constructor.

            **Parameters**

                reself

                    A logical variable. When ``True``, an instance of 
                    the object will be returned to the calling routine 
                    upon exit. The default value is ``False``.

            **Returns**

                The object if ``reself = True`` otherwise, ``None``.

                **NOTE**

                This method causes side-effects by manipulating
                the existing attributes of the object.

        """

        for key in kwargs.keys():
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif key == "dataFrame":
                setattr(self, "_dfref", wref.ref(kwargs[key]))
            else:
                raise Exception("Unrecognized input '" + key +
                                "' class attribute detected." + newline +
                                self._getDocString())

        ############################################################################################################################
        #### check columns presence
        ############################################################################################################################

        colnames, colindex = dfutils.getColNamesIndex(self._dfref().columns,
                                                      self.columns)

        ############################################################################################################################
        #### check rows presence. This must be checked here, because it depends on the integrity of the in input dataFrame.
        ############################################################################################################################

        if self.rows is None: self.rows = range(len(self._dfref().index))
        #rownames = self._dfref().index[self.rows]

        ############################################################################################################################
        #### compute the autocorrelations
        ############################################################################################################################

        self._nvar = len(colnames)
        self._nlag = len(self.rows)
        acf = np.zeros((self._nvar, self._nlag))

        try:

            from scipy.signal import correlate
            for cnt, ivar in enumerate(colindex):
                xdata = self._dfref().iloc[
                    self.rows, ivar].values.flatten() - np.mean(
                        self._dfref().iloc[self.rows, ivar].values.flatten())
                acf[cnt] = correlate(
                    xdata, xdata, mode="full")[self._nlag - 1:2 * self._nlag]
                acf[cnt] = acf[cnt] / acf[cnt, 0]

        except:

            if self._reportEnabled:
                err.warn(
                    msg=
                    "Failed to compute the Autocorrelation function of the input dataFrame."
                    + newline +
                    "This could likely be due to an error in importing the scipy Python library."
                    + newline +
                    "Please make sure you have the scipy library properly installed on your system."
                    + newline +
                    "You can do so by typing the following command on your Anaconda3 or Bash command prompt:"
                    + newline + newline +
                    "    pip install --user --upgrade scipy",
                    methodName=self._methodName,
                    marginTop=1,
                    marginBot=1)

        self.df = pd.DataFrame(np.transpose(acf))

        ############################################################################################################################
        #### specify columns/index names
        ############################################################################################################################

        colnames = ["ACF_" + colnames[i] for i in range(len(colnames))]
        self.df.columns = colnames

        ############################################################################################################################
        #### add SampleLogFunc to df for plot coloring, if exists
        ############################################################################################################################

        ccolumns = ()
        if "SampleLogFunc" in self._dfref().columns:
            ccolumns = "SampleLogFunc"
            self.df.insert(loc=0,
                           column=ccolumns,
                           value=self._dfref()[[ccolumns]].values.flatten(),
                           allow_duplicates=True)

        ############################################################################################################################
        #### add lags to df
        ############################################################################################################################

        self.df.insert(loc=0, column="Lag", value=[i for i in self.df.index])

        ############################################################################################################################
        #### graphics
        ############################################################################################################################

        self._plotTypeList = ["line", "scatter", "lineScatter"]

        self._progress.note(msg="adding the autocrrelation graphics tools... ",
                            end=newline,
                            pre=True)
        self.plot = Struct()
        self._resetPlot(resetType="hard")

        self.plot.reset = self._resetPlot

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

        if reself: return self
Exemplo n.º 5
0
    def plot(self):
        """

        .. py:method:: plot(self)

        Generate a heatmap of the requested columns from the selected columns of
        object's dataframe.

            **Parameters**

                None

            **Returns**

                None. However, this method causes side-effects by manipulating
                the existing attributes of the object.

        """

        if self.xticklabels_kws==(): self.xticklabels_kws={}
        if isinstance(self.xticklabels_kws,dict):
            if "horizontalalignment" not in self.xticklabels_kws.keys(): self.xticklabels_kws["horizontalalignment"] = "right"
            if "rotation" not in self.xticklabels_kws.keys(): self.xticklabels_kws["rotation"] = 45
        else:
            raise Exception ( "The input argument 'xticklabels_kws' must be a dictionary,\n"
                            + "each (key,value) pair of which represents an (attribute,value)\n"
                            + "of matplotlib library's Axes.set_xticklabels() method."
                            )

        if self.yticklabels_kws==(): self.yticklabels_kws={}
        if isinstance(self.yticklabels_kws,dict):
            if "horizontalalignment" not in self.yticklabels_kws.keys(): self.yticklabels_kws["horizontalalignment"] = "right"
            if "rotation" not in self.yticklabels_kws.keys(): self.yticklabels_kws["rotation"] = 45
        else:
            raise Exception ( "The input argument 'yticklabels_kws' must be a dictionary,\n"
                            + "each (key,value) pair of which represents an (attribute,value)\n"
                            + "of matplotlib library's Axes.set_yticklabels() method."
                            )

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

        if self.set_kws==(): self.set_kws={}
        figEnabled = self.figure_kws is not None
        if figEnabled:
            if self.figure_kws==(): self.figure_kws={}
            if isinstance(self.figure_kws,dict):
                if "dpi" not in self.figure_kws.keys(): self.figure_kws["dpi"] = 150
                if "facecolor" not in self.figure_kws.keys(): self.figure_kws["facecolor"] = "w"
                if "edgecolor" not in self.figure_kws.keys(): self.figure_kws["edgecolor"] = "w"
            else:
                raise Exception ( "The input argument 'figure_kws' must be a dictionary,\n"
                                + "each (key,value) pair of which represents an (attribute,value)\n"
                                + "of matplotlib library's figure() function."
                                )

        #########################
        if self._isdryrun: return
        #########################

        import seaborn as _sns
        from matplotlib import pyplot as _plt

        # moved here from the top because of dependency on seaborn _sns

        if self.heatmap_kws==(): self.heatmap_kws={}
        if isinstance(self.heatmap_kws,dict):
            if "square" not in self.heatmap_kws.keys(): self.heatmap_kws["square"] = True
            if "cmap" not in self.heatmap_kws.keys():
                self.heatmap_kws["cmap"] = _sns.diverging_palette   ( h_neg = self._colorStart
                                                                    , h_pos = self._colorEnd
                                                                    , n = self._colorCount
                                                                    )
        else:
            raise Exception ( "The input argument 'heatmap_kws' must be a dictionary,\n"
                            + "each (key,value) pair of which represents an (attribute,value)\n"
                            + "of Seaborn library's heatmap() function."
                            )

        # generate figure and axes if needed

        self.currentFig = ParaMonteFigure()
        if self.set_kws is not None: _sns.set(**self.set_kws)
        figEnabled = self.figure_kws is not None
        if figEnabled:
            self.currentFig.figure = _plt.figure( **self.figure_kws )
            self.currentFig.axes = _plt.subplot(1,1,1)
        else:
            self.currentFig.axes = _plt.gca()
            self.currentFig.figure = self.currentFig.axes.get_figure()

        # check data type

        noDataPassed = ""
        if self._dfref is None:
            noDataPassed = "It appears that no data has been passed for plotting.\n"
        elif not isinstance(self._dfref,_wref.ref):
            noDataPassed = "It appears that you have messed with the\ninternal representation of data in the object.\n"
        elif not isinstance(self._dfref(),_pd.DataFrame):
            noDataPassed = "The input data is not a pandas' dataframe.\n"
        if noDataPassed:
            raise Exception ( noDataPassed
                            + "The input data must be a pandas' dataframe.\n"
                            + "Please pass a dataFrame to the constructor or at\n"
                            + "the time of calling the object (which is callable with\n"
                            + "the same input arguments as the object's constructor."
                            )

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

        # check columns presence

        colnames, colindex = dfutils.getColNamesIndex(self._dfref().columns,self.columns)

        # check rows presence

        if self.rows is None:
            rowindex = range(len(self._dfref().index))
        else:
            rowindex = self.rows
        rownames = self._dfref().index[rowindex]

        # set up tick labels

        xtickExists = True
        if "xticklabels" in self.heatmap_kws.keys():
            if not any(self.heatmap_kws["xticklabels"]): xtickExists = False
        else:
            self.heatmap_kws["xticklabels"] = colnames

        ytickExists = True
        if "yticklabels" in self.heatmap_kws.keys():
            if not any(self.heatmap_kws["yticklabels"]): ytickExists = False
        else:
            self.heatmap_kws["yticklabels"] = rownames

        # plot data

        if self.annotPrecision is None:
            self.currentFig.axes = _sns.heatmap ( data = self._dfref().iloc[rowindex,colindex]
                                                , **self.heatmap_kws
                                                )
        else:
            self.currentFig.axes =_sns.heatmap  ( data = self._dfref().iloc[rowindex,colindex].round( decimals = self.annotPrecision )
                                                , **self.heatmap_kws
                                                )

        # configure the tick labels (orientation, ...)

        self.currentFig.axes.set_xticklabels( self.currentFig.axes.get_xticklabels()
                                            , **self.xticklabels_kws
                                            );

        self.currentFig.axes.set_yticklabels( self.currentFig.axes.get_yticklabels()
                                            , **self.yticklabels_kws
                                            );

        _plt.tight_layout()

        if figEnabled:

            # default figure size

            figWidth = 6.4  # inches
            figHeight = 4.8 # inches
            figWidthScale = 1
            figHeightScale = 1
            threshDimension = 10

            # scale only if ticklabels are present

            if xtickExists:
                figWidthScale = max( 1 , self._dfref().shape[1]/threshDimension )
                figWidth *= figWidthScale

            if ytickExists:
                figHeightScale = max( 1 , self._dfref().shape[0]/threshDimension )
                figHeight *= figHeightScale

            self.currentFig.figure.set_size_inches(figWidth,figHeight)

        if self.outputFile is not None:
            self.currentFig.figure.savefig  ( self.outputFile
                                            , bbox_inches = 'tight'
                                            , pad_inches = 0.0
                                            )

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

#!DEC$ endif
Exemplo n.º 6
0
    def plot(self):
        """

        .. py:method:: plot(self)

        Generate a line plot, or scatter plot, or both 
        from the selected columns of the object's dataframe.

            **Parameters**

                None

            **Returns**

                None. However, this method causes side-effects by manipulating 
                the existing attributes of the object.

        """

        # set plot type

        kdeEnabled = self.kdeplot_kws is not None

        if self.jointplot_kws is None:
            jointEnabled = False # not kdeEnabled
        else:
            kdeEnabled = False
            jointEnabled = True

        # set what to plot

        if self.kdeplot_kws==(): self.kdeplot_kws={}
        if isinstance(self.kdeplot_kws,dict):
            if "cbar"           not in self.kdeplot_kws.keys(): self.kdeplot_kws["cbar"]          = False
            if "cmap"           not in self.kdeplot_kws.keys(): self.kdeplot_kws["cmap"]          = "Blues"
            if "shade"          not in self.kdeplot_kws.keys(): self.kdeplot_kws["shade"]         = True
            if "n_levels"       not in self.kdeplot_kws.keys(): self.kdeplot_kws["n_levels"]      = 100
            if "shade_lowest"   not in self.kdeplot_kws.keys(): self.kdeplot_kws["shade_lowest"]  = True
        elif kdeEnabled:
            raise Exception ( "The input argument 'kdeplot_kws' must be None or a dictionary,\n"
                            + "each (key,value) pair of which represents an (attribute,value)\n"
                            + "of matplotlib library's plot() function."
                            )

        if self.jointplot_kws==(): self.jointplot_kws={}
        if isinstance(self.jointplot_kws,dict):
            if "height"             not in self.jointplot_kws.keys(): self.jointplot_kws["height"]        = 7
            if "space"              not in self.jointplot_kws.keys(): self.jointplot_kws["space"]         = 0
            if "kind"               not in self.jointplot_kws.keys(): self.jointplot_kws["kind"]          = "kde"
            if self.jointplot_kws["kind"] == "kde":
                if "cbar"           not in self.jointplot_kws.keys(): self.jointplot_kws["cbar"]          = False
                if "cmap"           not in self.jointplot_kws.keys(): self.jointplot_kws["cmap"]          = "Blues"
                if "shade"          not in self.jointplot_kws.keys(): self.jointplot_kws["shade"]         = True
                if "n_levels"       not in self.jointplot_kws.keys(): self.jointplot_kws["n_levels"]      = 100
                if "shade_lowest"   not in self.jointplot_kws.keys(): self.jointplot_kws["shade_lowest"]  = True
        elif jointEnabled:
            raise Exception ( "The input argument 'jointplot_kws' must be None or a dictionary,\n"
                            + "each (key,value) pair of which represents an (attribute,value)\n"
                            + "of matplotlib library's LineCollection() class."
                            )

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

        if self.set_kws==(): self.set_kws={}
        if "style" not in self.set_kws.keys(): self.set_kws["style"] = "ticks"
        figEnabled = self.figure_kws is not None
        if figEnabled:
            if self.figure_kws==(): self.figure_kws={}
            if isinstance(self.figure_kws,dict):
                if "dpi" not in self.figure_kws.keys(): self.figure_kws["dpi"] = 150
                if "facecolor" not in self.figure_kws.keys(): self.figure_kws["facecolor"] = "w"
                if "edgecolor" not in self.figure_kws.keys(): self.figure_kws["edgecolor"] = "w"
            else:
                raise Exception ( "The input argument 'figure_kws' must be a dictionary,\n"
                                + "each (key,value) pair of which represents an (attribute,value)\n"
                                + "of matplotlib library's figure() function."
                                )

        #########################
        if self._isdryrun: return
        #########################

        import seaborn as _sns
        from matplotlib import pyplot as _plt

        # generate figure and axes if needed

        self.currentFig = ParaMonteFigure()
        if figEnabled:
            if self.set_kws is not None: _sns.set(**self.set_kws)
            if kdeEnabled: self.currentFig.figure = _plt.figure( **self.figure_kws )
            #self.currentFig.axes = _plt.subplot(1,1,1)
        #else:
        #    self.currentFig.axes = _plt.gca()
        #    self.currentFig.figure = self.currentFig.axes.get_figure()

        # check data type

        noDataPassed = ""
        if self._dfref is None:
            noDataPassed = "It appears that no data has been passed for plotting.\n"
        elif not isinstance(self._dfref,_wref.ref):
            noDataPassed = "It appears that you have messed with the\ninternal representation of data in the object.\n"
        elif not isinstance(self._dfref(),_pd.DataFrame):
            noDataPassed = "The input data is not a pandas' dataframe.\n"
        if noDataPassed:
            raise Exception ( noDataPassed
                            + "The input data must be a pandas' dataframe.\n"
                            + "Please pass a dataFrame to the constructor or at\n"
                            + "the time of calling the object (which is callable with\n"
                            + "the same input arguments as the object's constructor."
                            )

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

        # check rows presence

        if self.rows is None:
            rowindex = range(len(self._dfref().index))
        else:
            rowindex = self.rows

        # check columns presence

        if self.xcolumn is None:
            xcolindex = [0]
            xcolnames = list(self._dfref().columns[xcolindex[0]:xcolindex[0]+1])
        else:
            xcolnames, xcolindex = dfutils.getColNamesIndex(self._dfref().columns,self.xcolumn)

        if self.ycolumn is None:
            ycolindex = [1]
            ycolnames = list(self._dfref().columns[ycolindex[0]:ycolindex[0]+1])
        else:
            ycolnames, ycolindex = dfutils.getColNamesIndex(self._dfref().columns,self.ycolumn)

        # check only one column is present

        if len(xcolnames)>1:
            raise Exception ( "Only one data column can be plotted on the x-axis.\n"
                            + "You have provided " + str(len(xcolnames)) + " columns:\n"
                            + str(xcolnames)
                            )
        if len(ycolnames)>1:
            raise Exception ( "Only one data column can be plotted on the y-axis.\n"
                            + "You have provided " + str(len(ycolnames)) + " columns:\n"
                            + str(ycolnames)
                            )

        # make plots

        if kdeEnabled:

            self.currentFig.kdeplot = _sns.kdeplot  ( data = self._dfref().iloc[rowindex,xcolindex[0]]
                                                    , data2 = self._dfref().iloc[rowindex,ycolindex[0]]
                                                    , **self.kdeplot_kws
                                                    )

        if jointEnabled:

            self.currentFig.jointplot = _sns.jointplot  ( x = self._dfref().iloc[rowindex,xcolindex[0]]
                                                        , y = self._dfref().iloc[rowindex,ycolindex[0]]
                                                        , **self.jointplot_kws
                                                        )

        _plt.tight_layout()
        if self.outputFile is not None:
            self.currentFig.figure.savefig  ( self.outputFile
                                            , bbox_inches = 'tight'
                                            , pad_inches = 0.0
                                            )

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

#!DEC$ endif
Exemplo n.º 7
0
    def plot(self):
        """

        .. py:method:: plot(self)

        Generate a scatter plot from the selected columns of the object's dataframe.

            **Parameters**

                None

            **Returns**

                None. However, this method causes side-effects by manipulating
                the existing attributes of the object.

        """

        # set what to plot

        scatterEnabled = self.scatter_kws is not None
        cEnabled = scatterEnabled and (self.ccolumns is not None)
        lgEnabled = (self.legend_kws
                     is not None) and (not (scatterEnabled and cEnabled))

        if self.scatter_kws == (): self.scatter_kws = {}
        if isinstance(self.scatter_kws, dict):
            if "s" not in self.scatter_kws.keys(): self.scatter_kws["s"] = 3
            if "cmap" not in self.scatter_kws.keys():
                self.scatter_kws["cmap"] = "autumn"
            if "alpha" not in self.scatter_kws.keys():
                self.scatter_kws["alpha"] = 1
            if "edgecolor" not in self.scatter_kws.keys():
                self.scatter_kws["edgecolor"] = None
            if "zorder" not in self.scatter_kws.keys():
                self.scatter_kws["zorder"] = 2
            #if cEnabled: self.scatter_kws["c"] = list(cdata)
        elif scatterEnabled:
            raise Exception(
                "The input argument 'scatter_kws' must be None or a dictionary,\n"
                +
                "each (key,value) pair of which represents an (attribute,value)\n"
                + "of matplotlib library's scatter() function.")

        if self.colorbar_kws == (): self.colorbar_kws = {}

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

        if self.set_kws == (): self.set_kws = {}
        figEnabled = self.figure_kws is not None
        if figEnabled:
            if self.figure_kws == (): self.figure_kws = {}
            if isinstance(self.figure_kws, dict):
                if "dpi" not in self.figure_kws.keys():
                    self.figure_kws["dpi"] = 150
                if "facecolor" not in self.figure_kws.keys():
                    self.figure_kws["facecolor"] = "w"
                if "edgecolor" not in self.figure_kws.keys():
                    self.figure_kws["edgecolor"] = "w"
            else:
                raise Exception(
                    "The input argument 'figure_kws' must be a dictionary,\n" +
                    "each (key,value) pair of which represents an (attribute,value)\n"
                    + "of matplotlib library's figure() function.")

        #########################
        if self._isdryrun: return
        #########################

        import seaborn as _sns
        from matplotlib import pyplot as _plt

        # generate figure and axes if needed

        self.currentFig = ParaMonteFigure()
        if self.set_kws is not None: _sns.set(**self.set_kws)
        if figEnabled:
            self.currentFig.figure = _plt.figure(**self.figure_kws)
            self.currentFig.axes = _plt.subplot(1, 1, 1)
        else:
            self.currentFig.axes = _plt.gca()
            self.currentFig.figure = self.currentFig.axes.get_figure()

        # check data type

        noDataPassed = False
        if self._dfref is None:
            noDataPassed = True
            fatalmsg = "It appears that no data has been passed for plotting.\n"
        elif not isinstance(self._dfref, _wref.ref):
            noDataPassed = True
            fatalmsg = "It appears that you have messed with the\ninternal representation of data in the object.\n"
        elif not isinstance(self._dfref(), _pd.DataFrame):
            noDataPassed = True
            fatalmsg = ""
        if noDataPassed:
            raise Exception(
                fatalmsg + "The input data must be a pandas' dataframe.\n" +
                "Please pass a dataFrame to the constructor or at\n" +
                "the time of calling the object (which is callable with\n" +
                "the same input arguments as the object's constructor.")

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

        # check rows presence

        if self.rows is None:
            rowindex = range(len(self._dfref().index))
        else:
            rowindex = self.rows

        # check columns presence

        if self.xcolumns is None:
            lgxicol = 0
            xcolindex = []
            xcolnames = ["Count"]
            xdata = _np.array(self._dfref().index[rowindex] +
                              self._indexOffset).flatten()
        else:
            xcolnames, xcolindex = dfutils.getColNamesIndex(
                self._dfref().columns, self.xcolumns)

        ycolnames, ycolindex = dfutils.getColNamesIndex(
            self._dfref().columns, self.ycolumns)

        # set scatter plot color data

        if cEnabled:
            if len(self.ccolumns) == 0:
                ccolindex = []
                ccolnames = ["Count"]
                cdata = _np.array(self._dfref().index[rowindex] +
                                  self._indexOffset).flatten()
            else:
                ccolnames, ccolindex = dfutils.getColNamesIndex(
                    self._dfref().columns, self.ccolumns)
        else:
            ccolindex = []
            ccolnames = []
            self.scatter_kws['c'] = None

        # check the lengths are consistent

        xcolindexlen = len(xcolindex)
        ycolindexlen = len(ycolindex)
        ccolindexlen = len(ccolindex)
        maxLenColumns = _np.max([xcolindexlen, ycolindexlen, ccolindexlen])

        if xcolindexlen != maxLenColumns and xcolindexlen > 1:
            raise Exception(
                "length of xcolumns must be either 1 or equal to the lengths of ycolumns or ccolumns."
            )
        if ycolindexlen != maxLenColumns and ycolindexlen > 1:
            raise Exception(
                "length of ycolumns must be either 1 or equal to the lengths of xcolumns or ccolumns."
            )
        if ccolindexlen != maxLenColumns and ccolindexlen > 1:
            raise Exception(
                "length of ccolumns must be either 1 or equal to the lengths of xcolumns or ycolumns."
            )

        # assign data in case of single column assignments

        if xcolindexlen == 1:
            lgxicol = 0
            xdata = self._dfref().iloc[rowindex, xcolindex].values.flatten()

        if ycolindexlen == 1:
            lgyicol = 0
            ydata = self._dfref().iloc[rowindex, ycolindex].values.flatten()

        if ccolindexlen == 1:
            cdata = self._dfref().iloc[rowindex, ccolindex].values.flatten()

        # add scatter plot

        if cEnabled and ccolindexlen < 2: self.scatter_kws["c"] = cdata

        if lgEnabled: lglabels = []
        for i in range(maxLenColumns):

            if xcolindexlen > 1:
                lgxicol = i
                xdata = self._dfref().iloc[rowindex,
                                           xcolindex[i]].values.flatten()
            if ycolindexlen > 1:
                lgyicol = i
                ydata = self._dfref().iloc[rowindex,
                                           ycolindex[i]].values.flatten()
            if ccolindexlen > 1:
                cdata = self._dfref().iloc[rowindex,
                                           ccolindex[i]].values.flatten()
                if cEnabled: self.scatter_kws["c"] = cdata

            if lgEnabled:
                if xcolindexlen < 2 and ycolindexlen > 1:
                    lglabels.append(ycolnames[lgyicol])
                elif xcolindexlen > 1 and ycolindexlen < 2:
                    lglabels.append(xcolnames[lgxicol])
                else:
                    lglabels.append(xcolnames[lgxicol] + "-" +
                                    ycolnames[lgyicol])

            if scatterEnabled:

                self.currentFig.scatter = self.currentFig.axes.scatter(
                    xdata, ydata, **self.scatter_kws)

        # add colorbar

        cbarEnabled = cEnabled and (self.colorbar_kws is not None) and (
            not hasattr(self.currentFig, "colorbar")) and (ccolindexlen < 2)
        if cbarEnabled:
            self.currentFig.colorbar = self.currentFig.figure.colorbar(
                mappable=self.currentFig.scatter,
                ax=self.currentFig.axes,
                **self.colorbar_kws)  #, orientation="vertical")
            self.currentFig.colorbar.set_label(label=", ".join(ccolnames))

        # add axis labels

        if xcolindexlen > 1:
            self.currentFig.axes.set_xlabel("Variable Values")
        else:
            self.currentFig.axes.set_xlabel(xcolnames[0])

        if ycolindexlen > 1:
            self.currentFig.axes.set_ylabel("Variable Values")
        else:
            self.currentFig.axes.set_ylabel(ycolnames[0])

        if lgEnabled:
            if self.legend_kws == (): self.legend_kws = {}
            if isinstance(self.legend_kws, dict):
                if "labels" not in self.legend_kws.keys():
                    self.legend_kws["labels"] = lglabels
                self.currentFig.legend = self.currentFig.axes.legend(
                    **self.legend_kws)
            else:
                raise Exception(
                    "The input argument 'legend_kws' must be a dictionary,\n" +
                    "each (key,value) pair of which represents an (attribute,value)\n"
                    + "of matplotlib library's legend() function.")

        _plt.tight_layout()
        if self.outputFile is not None:
            self.currentFig.figure.savefig(self.outputFile,
                                           bbox_inches='tight',
                                           pad_inches=0.0)
Exemplo n.º 8
0
    def plot(self):
        """

        .. py:method:: plot(self)

        Generate a histogram from the selected columns of object's dataframe.

            **Parameters**

                None

            **Returns**

                None. However, this method causes side-effects by manipulating 
                the existing attributes of the object.

        """

        if self.figure_kws == (): self.figure_kws = {}
        if self.figure_kws is not None:
            if isinstance(self.figure_kws, dict):
                if "dpi" not in self.figure_kws.keys():
                    self.figure_kws["dpi"] = 150
                if "facecolor" not in self.figure_kws.keys():
                    self.figure_kws["facecolor"] = "w"
                if "edgecolor" not in self.figure_kws.keys():
                    self.figure_kws["edgecolor"] = "w"
            else:
                raise Exception(
                    "The input argument 'figure_kws' must be a dictionary,\n" +
                    "each (key,value) pair of which represents an (attribute,value)\n"
                    + "of matplotlib library's figure() function.")

        if self.distplot_kws == (): self.distplot_kws = {}
        if isinstance(self.distplot_kws, dict):
            if "kde" not in self.distplot_kws.keys():
                self.distplot_kws["kde"] = False
            if "hist_kws" not in self.distplot_kws.keys():
                self.distplot_kws["hist_kws"] = dict()
            if "linewidth" not in self.distplot_kws["hist_kws"].keys():
                self.distplot_kws["hist_kws"]["linewidth"] = 0
            if "histtype" not in self.distplot_kws["hist_kws"].keys():
                self.distplot_kws["hist_kws"]["histtype"] = "stepfilled"
            self.distplot_kws["hist_kws"]["density"] = self.distplot_kws["kde"]
        else:
            raise Exception(
                "The input argument 'distplot_kws' must be a dictionary,\n" +
                "each (key,value) pair of which represents an (attribute,value)\n"
                + "of matplotlib library's figure() function.")

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

        if self.set_kws == (): self.set_kws = {}
        figEnabled = self.figure_kws is not None
        if figEnabled:
            if self.figure_kws == (): self.figure_kws = {}
            if isinstance(self.figure_kws, dict):
                if "dpi" not in self.figure_kws.keys():
                    self.figure_kws["dpi"] = 150
                if "facecolor" not in self.figure_kws.keys():
                    self.figure_kws["facecolor"] = "w"
                if "edgecolor" not in self.figure_kws.keys():
                    self.figure_kws["edgecolor"] = "w"
            else:
                raise Exception(
                    "The input argument 'figure_kws' must be a dictionary,\n" +
                    "each (key,value) pair of which represents an (attribute,value)\n"
                    + "of matplotlib library's figure() function.")

        #########################
        if self._isdryrun: return
        #########################

        import seaborn as _sns
        from matplotlib import pyplot as _plt

        # generate figure and axes if needed

        self.currentFig = ParaMonteFigure()
        figEnabled = self.figure_kws is not None
        if figEnabled:
            if self.set_kws is not None: _sns.set(**self.set_kws)
            self.currentFig.figure = _plt.figure(**self.figure_kws)
            self.currentFig.axes = _plt.subplot(1, 1, 1)
        else:
            self.currentFig.axes = _plt.gca()
            self.currentFig.figure = self.currentFig.axes.get_figure()

        # check data type

        noDataPassed = ""
        if self._dfref is None:
            noDataPassed = "It appears that no data has been passed for plotting.\n"
        elif not isinstance(self._dfref, _wref.ref):
            noDataPassed = "It appears that you have messed with the\ninternal representation of data in the object.\n"
        elif not isinstance(self._dfref(), _pd.DataFrame):
            noDataPassed = "The input data is not a pandas' dataframe.\n"
        if noDataPassed:
            raise Exception(
                noDataPassed +
                "The input data must be a pandas' dataframe.\n" +
                "Please pass a dataFrame to the constructor or at\n" +
                "the time of calling the object (which is callable with\n" +
                "the same input arguments as the object's constructor.")

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

        # check columns presence

        colnames, colindex = dfutils.getColNamesIndex(self._dfref().columns,
                                                      self.columns)

        # check rows presence

        if self.rows is None:
            rowindex = range(len(self._dfref().index))
        else:
            rowindex = self.rows

        selectedRows = self._dfref().index[rowindex]
        for icol in colindex:
            self.currentFig.axes = _sns.distplot(
                self._dfref().iloc[selectedRows, icol], **self.distplot_kws
                #, kde = False
                #, hist_kws = {"histtype": "step", "linewidth": 1, "alpha": 1}#, "color": "g"}
            )

        if self.distplot_kws["kde"]:
            self.currentFig.axes.set_ylabel("Probability Density")
        else:
            self.currentFig.axes.set_ylabel("Count")

        if len(colindex) == 1:
            self.currentFig.axes.set_xlabel(colnames[0])
        else:
            self.currentFig.axes.set_xlabel("Value")

        if self.legend_kws is not None:
            if self.legend_kws == (): self.legend_kws = {}
            if isinstance(self.legend_kws, dict):
                if self.legend_kws:
                    if "labels" not in self.legend_kws.keys():
                        self.legend_kws["labels"] = tuple(colnames)
                    self.currentFig.legend = self.currentFig.axes.legend(
                        **self.legend_kws)
                else:
                    self.currentFig.legend = self.currentFig.axes.legend(
                        labels=tuple(colnames))
            else:
                raise Exception(
                    "The input argument `legend_kws` must be a dictionary,\n" +
                    "each (key,value) pair of which represents an (attribute,value)\n"
                    + "of matplotlib library's legend() function.")

        _plt.tight_layout()

        if self.outputFile is not None:
            self.currentFig.axes.get_figure().savefig(self.outputFile,
                                                      bbox_inches='tight',
                                                      pad_inches=0.0)

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


#!DEC$ endif