Use matplotlib to compute boxplot statistics on e.g. timeseries data.
167472
def transform_dataframe(self, dataframe):
        
        grouping = self.get_grouping(dataframe)
        group_field = self.get_group_field()
        header_fields = self.get_header_fields()

        if "series" in grouping:
            # Unstack so each series is a column
            for i in range(len(header_fields) + 1):
                dataframe = dataframe.unstack()

        groups = {
            col: dataframe[col]
            for col in dataframe.columns
        }

        if "year" in grouping:
            interval = "year"
        elif "month" in grouping:
            interval = "month"
        else:
            interval = None

        # Compute stats for each column, potentially grouped by year
        series_infos = OrderedDict()
        for header, series in groups.items():
            if interval:
                series_stats = self.boxplots_for_interval(series, interval)
            else:
                series_stats = [self.compute_boxplot(series)]

            for series_stat in series_stats:
                if isinstance(header, tuple):
                    value_name = header[0]
                    col_values = header[1:]
                else:
                    value_name = header
                    col_values = []
                col_names = tuple(zip(dataframe.columns.names[1:], col_values))
                if interval in series_stat:
                    col_names += ((interval, series_stat[interval]),)
                series_infos.setdefault(col_names, dict(col_names))
                series_info = series_infos[col_names]
                for stat_name, val in series_stat.items():
                    if stat_name != interval:
                        series_info[value_name + '-' + stat_name] = val

        dataframe = DataFrame(list(series_infos.values()))
        if 'series' in grouping:
            index = header_fields + [group_field]
            unstack = len(header_fields)
            if interval:
                index = [interval] + index
                unstack += 1
        else:
            index = [interval]
            unstack = 0

        dataframe.set_index(index, inplace=True)
        dataframe.columns.name = ''
        for i in range(unstack):
            dataframe = dataframe.unstack()

        # Remove blank columns
        dataframe = dataframe.dropna(axis=1, how='all')
        return dataframe
90690
def plot(self, data):
    

    import IPython

    if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()):
      raise ValueError('Expect a dictionary where the values are all dataframes.')

    gfsg = GenericFeatureStatisticsGenerator()
    data = [{'name': k, 'table': self._remove_nonascii(v)} for k, v in six.iteritems(data)]
    data_proto = gfsg.ProtoFromDataFrames(data)
    protostr = base64.b64encode(data_proto.SerializeToString()).decode("utf-8")
    html_id = 'f' + datalab.utils.commands.Html.next_id()

    HTML_TEMPLATE = """<link rel="import" href="/nbextensions/gcpdatalab/extern/facets-jupyter.html" >
        <facets-overview id="{html_id}"></facets-overview>
        <script>
          document.querySelector("#{html_id}").protoInput = "{protostr}";
        </script>"""
    html = HTML_TEMPLATE.format(html_id=html_id, protostr=protostr)
    return IPython.core.display.HTML(html)
161042
def plot_fit(self, **kwargs):
        

        import matplotlib.pyplot as plt
        import seaborn as sns

        figsize = kwargs.get('figsize',(10,7))
        plt.figure(figsize=figsize)
        date_index = self.index[self.ar:self.data.shape[0]]
        mu, Y = self._model(self.latent_variables.get_z_values())
        plt.plot(date_index,Y,label='Data')
        plt.plot(date_index,mu,label='Filter',c='black')
        plt.title(self.data_name)
        plt.legend(loc=2)   
        plt.show()
1035291
def timeseries(self, dataframe=False):
        """"""

        closed_timeseries = self.closed.timeseries(dataframe=dataframe)
        opened_timeseries = self.opened.timeseries(dataframe=dataframe)
        return calculate_bmi(closed_timeseries, opened_timeseries)
697721
def timeseries():
    
    def method_builder(cls):
        method_doc = """Fetch the timeseries for this :class:`{0}`.

        Returns:

            The :class:`Timeseries` for this :class:`{0}`

        Keyword Args:

            **kwargs: The :class:`Timeseries` object constructor arguments.
        """.format(cls.__name__)

        def method(self, **kwargs):
            resource_id = None if self.is_singleton() else self.id
            return Timeseries(self._session, cls, resource_id, **kwargs)

        method.__doc__ = method_doc
        setattr(cls, 'timeseries', method)
        return cls
    return method_builder
363563
def plot_Sn_timesamples(PSP):
    
    TT = pot.stackel_triax()
    f,a = plt.subplots(2,1,figsize=[3.32,3.6])
    plt.subplots_adjust(hspace=0.,top=0.8)

    LowestPeriod = 2.*np.pi/38.86564386
    Times = np.array([2.,4.,8.,12.])
    Sr = np.arange(2,14,2)

    # Loop over length of integration window
    for i,P,C in zip(Times,['.','s','D','^'],['k','r','b','g']):
        diffact = np.zeros((len(Sr),3))
        difffreq = np.zeros((len(Sr),3))
        MAXGAPS = np.array([])
        # Loop over N_max
        for k,j in enumerate(Sr):
            NT = choose_NT(j)
            timeseries=np.linspace(0.,i*LowestPeriod,NT)
            results = odeint(pot.orbit_derivs2,PSP,timeseries,args=(TT,),rtol=1e-13,atol=1e-13)
            act,ang,n_vec,toy_aa, pars = find_actions(results, timeseries,N_matrix=j,ifprint=False,use_box=True)
            # Check all modes
            checks,maxgap = ced(n_vec,ua(toy_aa.T[3:].T,np.ones(3)))
            if len(maxgap)>0:
                maxgap = np.max(maxgap)
            else:
                maxgap = 0
            diffact[k] = act[:3]/TT.action(results[0])
            MAXGAPS = np.append(MAXGAPS,maxgap)
            difffreq[k] = ang[3:6]/TT.freq(results[0])
        size = 15
        if(P=='.'):
            size = 30
        LW = np.array(map(lambda i: 0.5+i*0.5, MAXGAPS))
        a[0].scatter(Sr,np.log10(np.abs(diffact.T[2]-1)),marker=P,s=size, color=C,facecolors="none",lw=LW,label=r'$T =\,$'+str(i)+r'$\,T_F$')
        a[1].scatter(Sr,np.log10(np.abs(difffreq.T[2]-1)),marker=P,s=size, color=C,facecolors="none", lw=LW)
    a[1].get_yticklabels()[-1].set_visible(False)
    a[0].set_xticklabels([])
    a[0].set_xlim(1,13)
    a[0].set_ylabel(r"$\log_{10}|J_3^\prime/J_{3, \rm true}-1|$")
    leg = a[0].legend(loc='upper center',bbox_to_anchor=(0.5,1.4),ncol=2, scatterpoints = 1)
    leg.draw_frame(False)
    a[1].set_xlim(1,13)
    a[1].set_xlabel(r'$N_{\rm max}$')
    a[1].set_ylabel(r"$\log_{10}|\Omega_3^\prime/\Omega_{3,\rm true}-1|$")
    plt.savefig('Sn_T_box.pdf',bbox_inches='tight')
835277
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
        ""
        if self._square_show_res:
            title = 'Ground truth\nPredictions'
            rows = int(np.ceil(math.sqrt(len(xs))))
            axs = subplots(rows, rows, imgsize=imgsize, figsize=figsize, title=title, weight='bold', size=12)
            for x,y,z,ax in zip(xs,ys,zs,axs.flatten()): x.show(ax=ax, title=f'{str(y)}\n{str(z)}', **kwargs)
            for ax in axs.flatten()[len(xs):]: ax.axis('off')
        else:
            title = 'Ground truth/Predictions'
            axs = subplots(len(xs), 2, imgsize=imgsize, figsize=figsize, title=title, weight='bold', size=14)
            for i,(x,y,z) in enumerate(zip(xs,ys,zs)):
                x.show(ax=axs[i,0], y=y, **kwargs)
                x.show(ax=axs[i,1], y=z, **kwargs)
406181
def tsne(adata, **kwargs) -> Union[Axes, List[Axes], None]:
    
    return plot_scatter(adata, 'tsne', **kwargs)
588887
def plot(self, x, y, **kw):
        
        return self.frame.plot(x,y,**kw)
873023
def make_plot(self):
        
        plot = Plot(figsize=self.figsize, dpi=self.dpi)
        ax = plot.gca(xscale='auto-gps')

        # handle user specified plot labels
        if self.args.legend:
            nlegargs = len(self.args.legend[0])
        else:
            nlegargs = 0
        if nlegargs > 0 and nlegargs != self.n_datasets:
            warnings.warn('The number of legends specified must match '
                          'the number of time series'
                          ' (channels * start times).  '
                          'There are {:d} series and {:d} legends'.format(
                            len(self.timeseries), len(self.args.legend)))
            nlegargs = 0    # don't use  them

        for i in range(0, self.n_datasets):
            series = self.timeseries[i]
            if nlegargs:
                label = self.args.legend[0][i]
            else:
                label = series.channel.name
            if self.usetex:
                label = label_to_latex(label)
            ax.plot(series, label=label)

        return plot
600657
def _boxf(self, serie):
        """"""
        serie_node = self.svg.serie(serie)
        # Note: q0 and q4 do not literally mean the zero-th quartile
        # and the fourth quartile, but rather the distance from 1.5 times
        # the inter-quartile range to Q1 and Q3, respectively.
        boxes = self.svg.node(serie_node['plot'], class_="boxes")

        metadata = serie.metadata.get(0)

        box = decorate(self.svg, self.svg.node(boxes, class_='box'), metadata)

        val = self._format(serie, 0)

        x_center, y_center = self._draw_box(
            box, serie.points[1:6], serie.outliers, serie.index, metadata
        )
        self._tooltip_data(
            box, val, x_center, y_center, "centered",
            self._get_x_label(serie.index)
        )
        self._static_value(serie_node, val, x_center, y_center, metadata)
292202
def compute_plot_size(plot):
    
    if isinstance(plot, GridBox):
        ndmapping = NdMapping({(x, y): fig for fig, y, x in plot.children}, kdims=['x', 'y'])
        cols = ndmapping.groupby('x')
        rows = ndmapping.groupby('y')
        width = sum([max([compute_plot_size(f)[0] for f in col]) for col in cols])
        height = sum([max([compute_plot_size(f)[1] for f in row]) for row in rows])
        return width, height
    elif isinstance(plot, (Div, ToolbarBox)):
        # Cannot compute size for Div or ToolbarBox
        return 0, 0
    elif isinstance(plot, (Row, Column, WidgetBox, Tabs)):
        if not plot.children: return 0, 0
        if isinstance(plot, Row) or (isinstance(plot, ToolbarBox) and plot.toolbar_location not in ['right', 'left']):
            w_agg, h_agg = (np.sum, np.max)
        elif isinstance(plot, Tabs):
            w_agg, h_agg = (np.max, np.max)
        else:
            w_agg, h_agg = (np.max, np.sum)
        widths, heights = zip(*[compute_plot_size(child) for child in plot.children])
        return w_agg(widths), h_agg(heights)
    elif isinstance(plot, (Figure, Chart)):
        if plot.plot_width:
            width = plot.plot_width
        else:
            width = plot.frame_width + plot.min_border_right + plot.min_border_left
        if plot.plot_height:
            height = plot.plot_height
        else:
            height = plot.frame_height + plot.min_border_bottom + plot.min_border_top
        return width, height
    elif isinstance(plot, (Plot, DataTable, Spacer)):
        return plot.width, plot.height
    else:
        return 0, 0
55106
def _compute(self):
        """"""
        if self._min:
            self._box.ymin = min(self._min, self.zero)
        if self._max:
            self._box.ymax = max(self._max, self.zero)
        self._x_pos = [
            x / self._len for x in range(self._len + 1)
        ] if self._len > 1 else [0, 1]  # Center if only one value

        self._points(self._x_pos)

        self._x_pos = [(i + .5) / self._len for i in range(self._len)]
1325658
def plot_fit(self,intervals=False,**kwargs):
        
        import matplotlib.pyplot as plt
        import seaborn as sns

        figsize = kwargs.get('figsize',(10,7))
        series_type = kwargs.get('series_type','Smoothed')

        if self.latent_variables.estimated is False:
            raise Exception("No latent variables estimated!")
        else:
            date_index = copy.deepcopy(self.index)
            date_index = date_index[:self.y.shape[0]+1]

            if series_type == 'Smoothed':
                mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())
            elif series_type == 'Filtered':
                mu, V, _, _, _ = self._model(self.data,self.latent_variables.get_z_values())
            else:
                mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())

            # Create smoothed/filtered aggregate series
            _, Z, _, _, _ = self._ss_matrices(self.latent_variables.get_z_values())
            smoothed_series = np.zeros(self.y.shape[0])

            for t in range(0,self.y.shape[0]):
                smoothed_series[t] = np.dot(Z[t],mu[:,t])

            plt.figure(figsize=figsize) 
            
            plt.subplot(self.z_no+1, 1, 1)
            plt.title(self.y_name + " Raw and " + series_type)  
            plt.plot(date_index,self.data,label='Data')
            plt.plot(date_index,smoothed_series,label=series_type,c='black')
            plt.legend(loc=2)

            for coef in range(0,self.z_no-1):
                V_coef = V[0][coef][:-1]    
                plt.subplot(self.z_no+1, 1, 2+coef)
                plt.title("Beta " + self.X_names[coef]) 

                if intervals == True:
                    alpha =[0.15*i/float(100) for i in range(50,12,-2)]
                    plt.fill_between(date_index[5:], mu[coef,0:mu.shape[1]-1][5:] + 1.98*np.sqrt(V_coef[5:]), mu[coef,0:mu.shape[1]-1][5:] - 1.98*np.sqrt(V_coef[5:]), alpha=0.15,label='95% C.I.') 
                plt.plot(date_index,mu[coef,0:mu.shape[1]-1],label='Data')
                plt.legend(loc=2)               
            
            plt.subplot(self.z_no+1, 1, self.z_no+1)
            plt.title("Measurement Error")
            plt.plot(date_index,self.data-smoothed_series,label='Irregular')
            plt.legend(loc=2)   

            plt.show()
960969
def setup():
    
    import sys
    already_loaded = 'matplotlib' in sys.modules

    # just make sure we can access matplotlib as mpl
    import matplotlib as mpl

    if not already_loaded:
        mpl.use('Agg')

    import matplotlib.pyplot as plt

    plt.style.use('seaborn')

    general_settings()

    import mpl_toolkits.axes_grid1 as axes_grid1
    axes_grid1
    return plt, mpl
519171
function groupSeriesByAxis(ecModel) {
    var result = [];
    var axisList = [];

    ecModel.eachSeriesByType('boxplot', function (seriesModel) {
        var baseAxis = seriesModel.getBaseAxis();
        var idx = zrUtil.indexOf(axisList, baseAxis);

        if (idx < 0) {
            idx = axisList.length;
            axisList[idx] = baseAxis;
            result[idx] = {axis: baseAxis, seriesModels: []};
        }

        result[idx].seriesModels.push(seriesModel);
    });

    return result;
}
219081
def tsplot(series, plotf, ax=None, **kwargs):
    import warnings
    
    warnings.warn("'tsplot' is deprecated and will be removed in a "
                  "future version. Please use Series.plot() instead.",
                  FutureWarning, stacklevel=2)

    # Used inferred freq is possible, need a test case for inferred
    if ax is None:
        import matplotlib.pyplot as plt
        ax = plt.gca()

    freq, series = _maybe_resample(series, ax, kwargs)

    # Set ax with freq info
    _decorate_axes(ax, freq, kwargs)
    ax._plot_data.append((series, plotf, kwargs))
    lines = plotf(ax, series.index._mpl_repr(), series.values, **kwargs)

    # set date formatter, locators and rescale limits
    format_dateaxis(ax, ax.freq, series.index)
    return lines