idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
25,600
def make_quantile_df ( data , draw_quantiles ) : dens = data [ 'density' ] . cumsum ( ) / data [ 'density' ] . sum ( ) ecdf = interp1d ( dens , data [ 'y' ] , assume_sorted = True ) ys = ecdf ( draw_quantiles ) violin_xminvs = interp1d ( data [ 'y' ] , data [ 'xminv' ] ) ( ys ) violin_xmaxvs = interp1d ( data [ 'y' ] , data [ 'xmaxv' ] ) ( ys ) data = pd . DataFrame ( { 'x' : interleave ( violin_xminvs , violin_xmaxvs ) , 'y' : np . repeat ( ys , 2 ) , 'group' : np . repeat ( np . arange ( 1 , len ( ys ) + 1 ) , 2 ) } ) return data
Return a dataframe with info needed to draw quantile segments
25,601
def from_geom ( geom ) : name = geom . params [ 'stat' ] kwargs = geom . _kwargs if ( not isinstance ( name , type ) and hasattr ( name , 'compute_layer' ) ) : return name if isinstance ( name , stat ) : return name elif isinstance ( name , type ) and issubclass ( name , stat ) : klass = name elif is_string ( name ) : if not name . startswith ( 'stat_' ) : name = 'stat_{}' . format ( name ) klass = Registry [ name ] else : raise PlotnineError ( 'Unknown stat of type {}' . format ( type ( name ) ) ) valid_kwargs = ( ( klass . aesthetics ( ) | klass . DEFAULT_PARAMS . keys ( ) ) & kwargs . keys ( ) ) params = { k : kwargs [ k ] for k in valid_kwargs } return klass ( geom = geom , ** params )
Return an instantiated stat object
25,602
def aesthetics ( cls ) : aesthetics = cls . REQUIRED_AES . copy ( ) calculated = get_calculated_aes ( cls . DEFAULT_AES ) for ae in set ( cls . DEFAULT_AES ) - set ( calculated ) : aesthetics . add ( ae ) return aesthetics
Return a set of all non - computed aesthetics for this stat .
25,603
def compute_layer ( cls , data , params , layout ) : check_required_aesthetics ( cls . REQUIRED_AES , list ( data . columns ) + list ( params . keys ( ) ) , cls . __name__ ) data = remove_missing ( data , na_rm = params . get ( 'na_rm' , False ) , vars = list ( cls . REQUIRED_AES | cls . NON_MISSING_AES ) , name = cls . __name__ , finite = True ) def fn ( pdata ) : if len ( pdata ) == 0 : return pdata pscales = layout . get_scales ( pdata [ 'PANEL' ] . iat [ 0 ] ) return cls . compute_panel ( pdata , pscales , ** params ) return groupby_apply ( data , 'PANEL' , fn )
Calculate statistics for this layers
25,604
def compute_panel ( cls , data , scales , ** params ) : if not len ( data ) : return type ( data ) ( ) stats = [ ] for _ , old in data . groupby ( 'group' ) : new = cls . compute_group ( old , scales , ** params ) unique = uniquecols ( old ) missing = unique . columns . difference ( new . columns ) u = unique . loc [ [ 0 ] * len ( new ) , missing ] . reset_index ( drop = True ) if u . empty and len ( u ) : u = type ( data ) ( ) df = pd . concat ( [ new , u ] , axis = 1 ) stats . append ( df ) stats = pd . concat ( stats , axis = 0 , ignore_index = True ) return stats
Calculate the stats of all the groups and return the results in a single dataframe .
25,605
def kde_scipy ( data , grid , ** kwargs ) : kde = gaussian_kde ( data . T , ** kwargs ) return kde . evaluate ( grid . T )
Kernel Density Estimation with Scipy
25,606
def kde_statsmodels_u ( data , grid , ** kwargs ) : kde = KDEUnivariate ( data ) kde . fit ( ** kwargs ) return kde . evaluate ( grid )
Univariate Kernel Density Estimation with Statsmodels
25,607
def kde_statsmodels_m ( data , grid , ** kwargs ) : kde = KDEMultivariate ( data , ** kwargs ) return kde . pdf ( grid )
Multivariate Kernel Density Estimation with Statsmodels
25,608
def kde_sklearn ( data , grid , ** kwargs ) : kde_skl = KernelDensity ( ** kwargs ) kde_skl . fit ( data ) log_pdf = kde_skl . score_samples ( grid ) return np . exp ( log_pdf )
Kernel Density Estimation with Scikit - learn
25,609
def kde ( data , grid , package , ** kwargs ) : if package == 'statsmodels' : package = 'statsmodels-m' func = KDE_FUNCS [ package ] return func ( data , grid , ** kwargs )
Kernel Density Estimation
25,610
def strategy ( data , params ) : width = params [ 'width' ] with suppress ( TypeError ) : iter ( width ) width = np . asarray ( width ) width = width [ data . index ] udata_group = data [ 'group' ] . drop_duplicates ( ) n = params . get ( 'n' , None ) if n is None : n = len ( udata_group ) if n == 1 : return data if not all ( [ col in data . columns for col in [ 'xmin' , 'xmax' ] ] ) : data [ 'xmin' ] = data [ 'x' ] data [ 'xmax' ] = data [ 'x' ] d_width = np . max ( data [ 'xmax' ] - data [ 'xmin' ] ) udata_group = udata_group . sort_values ( ) groupidx = match ( data [ 'group' ] , udata_group ) groupidx = np . asarray ( groupidx ) + 1 data [ 'x' ] = data [ 'x' ] + width * ( ( groupidx - 0.5 ) / n - 0.5 ) data [ 'xmin' ] = data [ 'x' ] - ( d_width / n ) / 2 data [ 'xmax' ] = data [ 'x' ] + ( d_width / n ) / 2 return data
Dodge overlapping interval
25,611
def parse_grid_facets ( facets ) : valid_seqs = [ "('var1', '.')" , "('var1', 'var2')" , "('.', 'var1')" , "((var1, var2), (var3, var4))" ] error_msg_s = ( "Valid sequences for specifying 'facets' look like" " {}" . format ( valid_seqs ) ) valid_forms = [ 'var1 ~ .' , 'var1 ~ var2' , '. ~ var1' , 'var1 + var2 ~ var3 + var4' , '. ~ func(var1) + func(var2)' , '. ~ func(var1+var3) + func(var2)' ] + valid_seqs error_msg_f = ( "Valid formula for 'facet_grid' look like" " {}" . format ( valid_forms ) ) if isinstance ( facets , ( tuple , list ) ) : if len ( facets ) != 2 : raise PlotnineError ( error_msg_s ) rows , cols = facets if isinstance ( rows , str ) : rows = [ ] if rows == '.' else [ rows ] if isinstance ( cols , str ) : cols = [ ] if cols == '.' else [ cols ] return rows , cols if not isinstance ( facets , str ) : raise PlotnineError ( error_msg_f ) try : lhs , rhs = facets . split ( '~' ) except ValueError : raise PlotnineError ( error_msg_s ) else : lhs = lhs . strip ( ) rhs = rhs . strip ( ) lhs = ensure_var_or_dot ( lhs ) rhs = ensure_var_or_dot ( rhs ) lsplitter = ' + ' if ' + ' in lhs else '+' rsplitter = ' + ' if ' + ' in rhs else '+' if lhs == '.' : rows = [ ] else : rows = [ var . strip ( ) for var in lhs . split ( lsplitter ) ] if rhs == '.' : cols = [ ] else : cols = [ var . strip ( ) for var in rhs . split ( rsplitter ) ] return rows , cols
Return two lists of facetting variables for the rows & columns
25,612
def expand_default ( self , scale , discrete = ( 0 , 0.6 , 0 , 0.6 ) , continuous = ( 0.05 , 0 , 0.05 , 0 ) ) : if is_waive ( scale . expand ) : if isinstance ( scale , scale_discrete ) : return discrete elif isinstance ( scale , scale_continuous ) : return continuous else : name = scale . __class__ . __name__ msg = "Failed to expand scale '{}'" . format ( name ) raise PlotnineError ( msg ) else : return scale . expand
Expand a single scale
25,613
def dict_to_table ( header , contents ) : def to_text ( row ) : name , value = row m = max_col1_size + 1 - len ( name ) spacing = ' ' * m return '' . join ( [ name , spacing , value ] ) thead = tuple ( str ( col ) for col in header ) rows = [ ] for name , value in contents . items ( ) : if value != '' : if isinstance ( value , str ) : value = "'{}'" . format ( value ) value = ':py:`{}`' . format ( value ) rows . append ( ( name , value ) ) n = np . max ( [ len ( header [ 0 ] ) ] + [ len ( col1 ) for col1 , _ in rows ] ) hborder = tuple ( '=' * n for col in header ) rows = [ hborder , thead , hborder ] + rows + [ hborder ] max_col1_size = np . max ( [ len ( col1 ) for col1 , _ in rows ] ) table = '\n' . join ( [ to_text ( row ) for row in rows ] ) return table
Convert dict to table
25,614
def make_signature ( name , params , common_params , common_param_values ) : tokens = [ ] seen = set ( ) def tokens_append ( key , value ) : if isinstance ( value , str ) : value = "'{}'" . format ( value ) tokens . append ( '{}={}' . format ( key , value ) ) for key in common_params : seen . add ( key ) try : value = params [ key ] except KeyError : value = common_param_values [ key ] tokens_append ( key , value ) for key in ( set ( params ) - seen ) : tokens_append ( key , params [ key ] ) s1 = name + '(' s2 = ', ' . join ( tokens ) + ', **kwargs)' line_width = 78 - len ( s1 ) indent_spaces = ' ' * ( len ( s1 ) + 4 ) newline_and_space = '\n' + indent_spaces s2_lines = wrap ( s2 , width = line_width ) return s1 + newline_and_space . join ( s2_lines )
Create a signature for a geom or stat
25,615
def docstring_section_lines ( docstring , section_name ) : lines = [ ] inside_section = False underline = '-' * len ( section_name ) expect_underline = False for line in docstring . splitlines ( ) : _line = line . strip ( ) . lower ( ) if expect_underline : expect_underline = False if _line == underline : inside_section = True continue if _line == section_name : expect_underline = True elif _line in DOCSTRING_SECTIONS : break elif inside_section : lines . append ( line ) return '\n' . join ( lines )
Return a section of a numpydoc string
25,616
def parameters_str_to_dict ( param_section ) : d = OrderedDict ( ) previous_param = None param_desc = None for line in param_section . split ( '\n' ) : param = param_spec ( line ) if param : if previous_param : d [ previous_param ] = '\n' . join ( param_desc ) param_desc = [ line ] previous_param = param elif param_desc : param_desc . append ( line ) if previous_param : d [ previous_param ] = '\n' . join ( param_desc ) return d
Convert a param section to a dict
25,617
def document_geom ( geom ) : docstring = dedent ( geom . __doc__ ) signature = make_signature ( geom . __name__ , geom . DEFAULT_PARAMS , common_geom_params , common_geom_param_values ) usage = GEOM_SIGNATURE_TPL . format ( signature = signature ) contents = OrderedDict ( ( '**{}**' . format ( ae ) , '' ) for ae in sorted ( geom . REQUIRED_AES ) ) if geom . DEFAULT_AES : d = geom . DEFAULT_AES . copy ( ) d [ 'group' ] = '' contents . update ( sorted ( d . items ( ) ) ) table = dict_to_table ( ( 'Aesthetic' , 'Default value' ) , contents ) aesthetics_table = AESTHETICS_TABLE_TPL . format ( table = table ) tpl = dedent ( geom . _aesthetics_doc . lstrip ( '\n' ) ) aesthetics_doc = tpl . format ( aesthetics_table = aesthetics_table ) aesthetics_doc = indent ( aesthetics_doc , ' ' * 4 ) d = geom . DEFAULT_PARAMS common_parameters = GEOM_PARAMS_TPL . format ( default_stat = d [ 'stat' ] , default_position = d [ 'position' ] , default_na_rm = d [ 'na_rm' ] , default_inherit_aes = d . get ( 'inherit_aes' , True ) , _aesthetics_doc = aesthetics_doc , ** common_params_doc ) docstring = docstring . replace ( '{usage}' , usage ) docstring = docstring . replace ( '{common_parameters}' , common_parameters ) geom . __doc__ = docstring return geom
Create a structured documentation for the geom
25,618
def document_stat ( stat ) : docstring = dedent ( stat . __doc__ ) signature = make_signature ( stat . __name__ , stat . DEFAULT_PARAMS , common_stat_params , common_stat_param_values ) usage = STAT_SIGNATURE_TPL . format ( signature = signature ) contents = OrderedDict ( ( '**{}**' . format ( ae ) , '' ) for ae in sorted ( stat . REQUIRED_AES ) ) contents . update ( sorted ( stat . DEFAULT_AES . items ( ) ) ) table = dict_to_table ( ( 'Aesthetic' , 'Default value' ) , contents ) aesthetics_table = AESTHETICS_TABLE_TPL . format ( table = table ) tpl = dedent ( stat . _aesthetics_doc . lstrip ( '\n' ) ) aesthetics_doc = tpl . format ( aesthetics_table = aesthetics_table ) aesthetics_doc = indent ( aesthetics_doc , ' ' * 4 ) d = stat . DEFAULT_PARAMS common_parameters = STAT_PARAMS_TPL . format ( default_geom = d [ 'geom' ] , default_position = d [ 'position' ] , default_na_rm = d [ 'na_rm' ] , _aesthetics_doc = aesthetics_doc , ** common_params_doc ) docstring = docstring . replace ( '{usage}' , usage ) docstring = docstring . replace ( '{common_parameters}' , common_parameters ) stat . __doc__ = docstring return stat
Create a structured documentation for the stat
25,619
def document_scale ( cls ) : params_list = [ ] cls_param_string = docstring_parameters_section ( cls ) cls_param_dict = parameters_str_to_dict ( cls_param_string ) cls_params = set ( cls_param_dict . keys ( ) ) for i , base in enumerate ( cls . __bases__ ) : base_param_string = param_string = docstring_parameters_section ( base ) base_param_dict = parameters_str_to_dict ( base_param_string ) base_params = set ( base_param_dict . keys ( ) ) duplicate_params = base_params & cls_params for param in duplicate_params : del base_param_dict [ param ] if duplicate_params : param_string = parameters_dict_to_str ( base_param_dict ) if i == 0 : param_string = param_string . strip ( ) params_list . append ( param_string ) cls_params |= base_params superclass_parameters = '\n' . join ( params_list ) cls . __doc__ = cls . __doc__ . format ( superclass_parameters = superclass_parameters ) return cls
Create a documentation for a scale
25,620
def document ( cls ) : if cls . __doc__ is None : return cls baseclass_name = cls . mro ( ) [ - 2 ] . __name__ try : return DOC_FUNCTIONS [ baseclass_name ] ( cls ) except KeyError : return cls
Decorator to document a class
25,621
def _draw_using_figure ( self , figure , axs ) : self = deepcopy ( self ) self . _build ( ) self . theme = self . theme or theme_get ( ) self . figure = figure self . axs = axs try : with mpl . rc_context ( ) : self . theme . apply_rcparams ( ) self . _setup_parameters ( ) self . _draw_layers ( ) self . _draw_facet_labels ( ) self . _draw_legend ( ) self . _apply_theme ( ) except Exception as err : if self . figure is not None : plt . close ( self . figure ) raise err return self
Draw onto already created figure and axes
25,622
def _build ( self ) : if not self . layers : self += geom_blank ( ) self . layout = Layout ( ) layers = self . layers scales = self . scales layout = self . layout layers . generate_data ( self . data ) layout . setup ( layers , self ) layers . compute_aesthetics ( self ) layers . transform ( scales ) layout . train_position ( layers , scales . x , scales . y ) layout . map_position ( layers ) layers . compute_statistic ( layout ) layers . map_statistic ( self ) scales . add_missing ( ( 'x' , 'y' ) ) layers . setup_data ( ) layers . compute_position ( layout ) layout . reset_position_scales ( ) layout . train_position ( layers , scales . x , scales . y ) layout . map_position ( layers ) npscales = scales . non_position_scales ( ) if len ( npscales ) : layers . train ( npscales ) layers . map ( npscales ) layout . setup_panel_params ( self . coordinates ) layers . use_defaults ( ) layers . finish_statistics ( ) layout . finish_data ( layers )
Build ggplot for rendering .
25,623
def _setup_parameters ( self ) : self . facet . set ( layout = self . layout , theme = self . theme , coordinates = self . coordinates , figure = self . figure , axs = self . axs ) self . layout . axs = self . axs self . theme . figure = self . figure
Set facet properties
25,624
def _create_figure ( self ) : if get_option ( 'close_all_figures' ) : plt . close ( 'all' ) figure = plt . figure ( ) axs = self . facet . make_axes ( figure , self . layout . layout , self . coordinates ) figure . _themeable = { } self . figure = figure self . axs = axs return figure , axs
Create Matplotlib figure and axes
25,625
def _draw_facet_labels ( self ) : for pidx , layout_info in self . layout . layout . iterrows ( ) : panel_params = self . layout . panel_params [ pidx ] self . facet . set_breaks_and_labels ( panel_params , layout_info , pidx ) self . facet . draw_label ( layout_info , pidx )
Draw facet labels a . k . a strip texts
25,626
def _draw_legend ( self ) : legend_box = self . guides . build ( self ) if not legend_box : return figure = self . figure left = figure . subplotpars . left right = figure . subplotpars . right top = figure . subplotpars . top bottom = figure . subplotpars . bottom W , H = figure . get_size_inches ( ) position = self . guides . position get_property = self . theme . themeables . property spacing = 0.1 strip_margin_x = 0 strip_margin_y = 0 with suppress ( KeyError ) : spacing = get_property ( 'legend_box_spacing' ) with suppress ( KeyError ) : strip_margin_x = get_property ( 'strip_margin_x' ) with suppress ( KeyError ) : strip_margin_y = get_property ( 'strip_margin_y' ) right_strip_width = self . facet . strip_size ( 'right' ) top_strip_height = self . facet . strip_size ( 'top' ) if position == 'right' : loc = 6 pad = right_strip_width * ( 1 + strip_margin_x ) + spacing x = right + pad / W y = 0.5 elif position == 'left' : loc = 7 x = left - spacing / W y = 0.5 elif position == 'top' : loc = 8 x = 0.5 pad = top_strip_height * ( 1 + strip_margin_y ) + spacing y = top + pad / H elif position == 'bottom' : loc = 9 x = 0.5 y = bottom - spacing / H else : loc = 10 x , y = position anchored_box = AnchoredOffsetbox ( loc = loc , child = legend_box , pad = 0. , frameon = False , bbox_to_anchor = ( x , y ) , bbox_transform = figure . transFigure , borderpad = 0. ) anchored_box . set_zorder ( 90.1 ) self . figure . _themeable [ 'legend_background' ] = anchored_box ax = self . axs [ 0 ] ax . add_artist ( anchored_box )
Draw legend onto the figure
25,627
def _draw_labels ( self ) : figure = self . figure get_property = self . theme . themeables . property try : margin = get_property ( 'axis_title_x' , 'margin' ) except KeyError : pad_x = 5 else : pad_x = margin . get_as ( 't' , 'pt' ) try : margin = get_property ( 'axis_title_y' , 'margin' ) except KeyError : pad_y = 5 else : pad_y = margin . get_as ( 'r' , 'pt' ) labels = self . coordinates . labels ( { 'x' : self . layout . xlabel ( self . labels ) , 'y' : self . layout . ylabel ( self . labels ) } ) xlabel = self . facet . last_ax . set_xlabel ( labels [ 'x' ] , labelpad = pad_x ) ylabel = self . facet . first_ax . set_ylabel ( labels [ 'y' ] , labelpad = pad_y ) xlabel . set_transform ( mtransforms . blended_transform_factory ( figure . transFigure , mtransforms . IdentityTransform ( ) ) ) ylabel . set_transform ( mtransforms . blended_transform_factory ( mtransforms . IdentityTransform ( ) , figure . transFigure ) ) figure . _themeable [ 'axis_title_x' ] = xlabel figure . _themeable [ 'axis_title_y' ] = ylabel
Draw x and y labels onto the figure
25,628
def _draw_title ( self ) : figure = self . figure title = self . labels . get ( 'title' , '' ) rcParams = self . theme . rcParams get_property = self . theme . themeables . property top = figure . subplotpars . top W , H = figure . get_size_inches ( ) try : fontsize = get_property ( 'plot_title' , 'size' ) except KeyError : fontsize = float ( rcParams . get ( 'font.size' , 12 ) ) try : linespacing = get_property ( 'plot_title' , 'linespacing' ) except KeyError : linespacing = 1.2 try : margin = get_property ( 'plot_title' , 'margin' ) except KeyError : pad = 0.09 else : pad = margin . get_as ( 'b' , 'in' ) try : strip_margin_x = get_property ( 'strip_margin_x' ) except KeyError : strip_margin_x = 0 line_size = fontsize / 72.27 num_lines = len ( title . split ( '\n' ) ) title_size = line_size * linespacing * num_lines strip_height = self . facet . strip_size ( 'top' ) strip_height *= ( 1 + strip_margin_x ) x = 0.5 y = top + ( strip_height + title_size / 2 + pad ) / H text = figure . text ( x , y , title , ha = 'center' , va = 'center' ) figure . _themeable [ 'plot_title' ] = text
Draw title onto the figure
25,629
def _apply_theme ( self ) : self . theme . apply_axs ( self . axs ) self . theme . apply_figure ( self . figure )
Apply theme attributes to Matplotlib objects
25,630
def _save_filename ( self , ext ) : hash_token = abs ( self . __hash__ ( ) ) return 'plotnine-save-{}.{}' . format ( hash_token , ext )
Default filename used by the save method
25,631
def save ( self , filename = None , format = None , path = None , width = None , height = None , units = 'in' , dpi = None , limitsize = True , verbose = True , ** kwargs ) : fig_kwargs = { 'bbox_inches' : 'tight' , 'format' : format } fig_kwargs . update ( kwargs ) figure = [ None ] if filename is None : ext = format if format else 'pdf' filename = self . _save_filename ( ext ) if path : filename = os . path . join ( path , filename ) self = deepcopy ( self ) self . theme = self . theme or theme_get ( ) if width is not None and height is not None : width = to_inches ( width , units ) height = to_inches ( height , units ) self += theme ( figure_size = ( width , height ) ) elif ( width is None and height is not None or width is not None and height is None ) : raise PlotnineError ( "You must specify both width and height" ) width , height = self . theme . themeables . property ( 'figure_size' ) if limitsize and ( width > 25 or height > 25 ) : raise PlotnineError ( "Dimensions (width={}, height={}) exceed 25 inches " "(height and width are specified in inches/cm/mm, " "not pixels). If you are sure you want these " "dimensions, use 'limitsize=False'." . format ( width , height ) ) if dpi is None : try : self . theme . themeables . property ( 'dpi' ) except KeyError : self . theme = self . theme + theme ( dpi = 100 ) else : self . theme = self . theme + theme ( dpi = dpi ) if verbose : warn ( "Saving {0} x {1} {2} image." . format ( from_inches ( width , units ) , from_inches ( height , units ) , units ) , PlotnineWarning ) warn ( 'Filename: {}' . format ( filename ) , PlotnineWarning ) def _save ( ) : fig = figure [ 0 ] = self . draw ( ) facecolor = fig . get_facecolor ( ) edgecolor = fig . get_edgecolor ( ) if edgecolor : fig_kwargs [ 'facecolor' ] = facecolor if edgecolor : fig_kwargs [ 'edgecolor' ] = edgecolor fig_kwargs [ 'frameon' ] = True fig . savefig ( filename , ** fig_kwargs ) try : _save ( ) except Exception as err : figure [ 0 ] and plt . close ( figure [ 0 ] ) raise err else : figure [ 0 ] and plt . close ( figure [ 0 ] )
Save a ggplot object as an image file
25,632
def mavg ( data , xseq , ** params ) : window = params [ 'method_args' ] [ 'window' ] rolling = data [ 'y' ] . rolling ( ** params [ 'method_args' ] ) y = rolling . mean ( ) [ window : ] n = len ( data ) stderr = rolling . std ( ) [ window : ] x = data [ 'x' ] [ window : ] data = pd . DataFrame ( { 'x' : x , 'y' : y } ) data . reset_index ( inplace = True , drop = True ) if params [ 'se' ] : df = n - window data [ 'ymin' ] , data [ 'ymax' ] = tdist_ci ( y , df , stderr , params [ 'level' ] ) data [ 'se' ] = stderr return data
Fit moving average
25,633
def gpr ( data , xseq , ** params ) : try : from sklearn import gaussian_process except ImportError : raise PlotnineError ( "To use gaussian process smoothing, " "You need to install scikit-learn." ) kwargs = params [ 'method_args' ] if not kwargs : warnings . warn ( "See sklearn.gaussian_process.GaussianProcessRegressor " "for parameters to pass in as 'method_args'" , PlotnineWarning ) regressor = gaussian_process . GaussianProcessRegressor ( ** kwargs ) X = np . atleast_2d ( data [ 'x' ] ) . T n = len ( data ) Xseq = np . atleast_2d ( xseq ) . T regressor . fit ( X , data [ 'y' ] ) data = pd . DataFrame ( { 'x' : xseq } ) if params [ 'se' ] : y , stderr = regressor . predict ( Xseq , return_std = True ) data [ 'y' ] = y data [ 'se' ] = stderr data [ 'ymin' ] , data [ 'ymax' ] = tdist_ci ( y , n - 1 , stderr , params [ 'level' ] ) else : data [ 'y' ] = regressor . predict ( Xseq , return_std = True ) return data
Fit gaussian process
25,634
def tdist_ci ( x , df , stderr , level ) : q = ( 1 + level ) / 2 delta = stats . t . ppf ( q , df ) * stderr return x - delta , x + delta
Confidence Intervals using the t - distribution
25,635
def wls_prediction_std ( res , exog = None , weights = None , alpha = 0.05 , interval = 'confidence' ) : covb = res . cov_params ( ) if exog is None : exog = res . model . exog predicted = res . fittedvalues if weights is None : weights = res . model . weights else : exog = np . atleast_2d ( exog ) if covb . shape [ 1 ] != exog . shape [ 1 ] : raise ValueError ( 'wrong shape of exog' ) predicted = res . model . predict ( res . params , exog ) if weights is None : weights = 1. else : weights = np . asarray ( weights ) if weights . size > 1 and len ( weights ) != exog . shape [ 0 ] : raise ValueError ( 'weights and exog do not have matching shape' ) predvar = res . mse_resid / weights ip = ( exog * np . dot ( covb , exog . T ) . T ) . sum ( 1 ) if interval == 'confidence' : predstd = np . sqrt ( ip ) elif interval == 'prediction' : predstd = np . sqrt ( ip + predvar ) tppf = stats . t . isf ( alpha / 2. , res . df_resid ) interval_u = predicted + tppf * predstd interval_l = predicted - tppf * predstd return predstd , interval_l , interval_u
calculate standard deviation and confidence interval
25,636
def setup ( self , layers , plot ) : data = [ l . data for l in layers ] self . facet = plot . facet self . facet . setup_params ( data ) data = self . facet . setup_data ( data ) self . coord = plot . coordinates self . coord . setup_params ( data ) data = self . coord . setup_data ( data ) data = self . facet . setup_data ( data ) self . layout = self . facet . compute_layout ( data ) self . layout = self . coord . setup_layout ( self . layout ) self . check_layout ( ) for layer , ldata in zip ( layers , data ) : layer . data = self . facet . map ( ldata , self . layout )
Create a layout for the panels
25,637
def train_position ( self , layers , x_scale , y_scale ) : layout = self . layout if self . panel_scales_x is None and x_scale : result = self . facet . init_scales ( layout , x_scale , None ) self . panel_scales_x = result . x if self . panel_scales_y is None and y_scale : result = self . facet . init_scales ( layout , None , y_scale ) self . panel_scales_y = result . y self . facet . train_position_scales ( self , layers )
Create all the required x & y panel_scales y_scales and set the ranges for each scale according to the data .
25,638
def get_scales ( self , i ) : bool_idx = ( np . asarray ( self . layout [ 'PANEL' ] ) == i ) xsc = None ysc = None if self . panel_scales_x : idx = self . layout . loc [ bool_idx , 'SCALE_X' ] . values [ 0 ] xsc = self . panel_scales_x [ idx - 1 ] if self . panel_scales_y : idx = self . layout . loc [ bool_idx , 'SCALE_Y' ] . values [ 0 ] ysc = self . panel_scales_y [ idx - 1 ] return types . SimpleNamespace ( x = xsc , y = ysc )
Return x & y scales for panel i
25,639
def reset_position_scales ( self ) : if not self . facet . shrink : return with suppress ( AttributeError ) : self . panel_scales_x . reset ( ) with suppress ( AttributeError ) : self . panel_scales_y . reset ( )
Reset x and y scales
25,640
def setup_panel_params ( self , coord ) : if not self . panel_scales_x : raise PlotnineError ( 'Missing an x scale' ) if not self . panel_scales_y : raise PlotnineError ( 'Missing a y scale' ) self . panel_params = [ ] cols = [ 'SCALE_X' , 'SCALE_Y' ] for i , j in self . layout [ cols ] . itertuples ( index = False ) : i , j = i - 1 , j - 1 params = coord . setup_panel_params ( self . panel_scales_x [ i ] , self . panel_scales_y [ j ] ) self . panel_params . append ( params )
Calculate the x & y range & breaks information for each panel
25,641
def finish_data ( self , layers ) : for layer in layers : layer . data = self . facet . finish_data ( layer . data , self )
Modify data before it is drawn out by the geom
25,642
def _set_defaults ( self ) : valid_locations = { 'top' , 'bottom' , 'left' , 'right' } horizontal_locations = { 'left' , 'right' } get_property = self . theme . themeables . property margin_location_lookup = { 't' : 'b' , 'b' : 't' , 'l' : 'r' , 'r' : 'l' } self . label_position = self . label_position or 'right' if self . label_position not in valid_locations : msg = "label position '{}' is invalid" raise PlotnineError ( msg . format ( self . label_position ) ) name = 'legend_text_{}' . format ( self . __class__ . __name__ . split ( '_' ) [ - 1 ] ) loc = margin_location_lookup [ self . label_position [ 0 ] ] try : margin = get_property ( name , 'margin' ) except KeyError : self . _label_margin = 3 else : self . _label_margin = margin . get_as ( loc , 'pt' ) if self . direction is None : if self . label_position in horizontal_locations : self . direction = 'vertical' else : self . direction = 'horizontal' if self . title_position is None : if self . direction == 'vertical' : self . title_position = 'top' elif self . direction == 'horizontal' : self . title_position = 'left' if self . title_position not in valid_locations : msg = "title position '{}' is invalid" raise PlotnineError ( msg . format ( self . title_position ) ) tmp = 'left' if self . direction == 'vertical' else 'center' self . _title_align = self . _default ( 'legend_title_align' , tmp ) try : position = get_property ( 'legend_position' ) except KeyError : position = 'right' if position in { 'top' , 'bottom' } : tmp = 'horizontal' else : tmp = 'vertical' self . direction = self . _default ( 'legend_direction' , tmp ) loc = margin_location_lookup [ self . title_position [ 0 ] ] try : margin = get_property ( 'legend_title' , 'margin' ) except KeyError : self . _title_margin = 8 else : self . _title_margin = margin . get_as ( loc , 'pt' ) try : self . _legend_margin = get_property ( 'legend_margin' ) except KeyError : self . _legend_margin = 10 try : self . _legend_entry_spacing_x = get_property ( 'legend_entry_spacing_x' ) except KeyError : self . _legend_entry_spacing_x = 5 try : self . _legend_entry_spacing_y = get_property ( 'legend_entry_spacing_y' ) except KeyError : self . _legend_entry_spacing_y = 2
Set configuration parameters for drawing guide
25,643
def legend_aesthetics ( self , layer , plot ) : l = layer legend_ae = set ( self . key . columns ) - { 'label' } all_ae = ( l . mapping . keys ( ) | ( plot . mapping if l . inherit_aes else set ( ) ) | l . stat . DEFAULT_AES . keys ( ) ) geom_ae = l . geom . REQUIRED_AES | l . geom . DEFAULT_AES . keys ( ) matched = all_ae & geom_ae & legend_ae matched = list ( matched - set ( l . geom . aes_params ) ) return matched
Return the aesthetics that contribute to the legend
25,644
def train_df ( self , df ) : aesthetics = sorted ( set ( self . aesthetics ) & set ( df . columns ) ) for ae in aesthetics : self . train ( df [ ae ] )
Train scale from a dataframe
25,645
def train ( self , scale , aesthetic = None ) : if aesthetic is None : aesthetic = scale . aesthetics [ 0 ] breaks = scale . get_breaks ( ) if isinstance ( breaks , OrderedDict ) : if all ( [ np . isnan ( x ) for x in breaks . values ( ) ] ) : return None elif not len ( breaks ) or all ( np . isnan ( breaks ) ) : return None with suppress ( AttributeError ) : breaks = list ( breaks . keys ( ) ) key = pd . DataFrame ( { aesthetic : scale . map ( breaks ) , 'label' : scale . get_labels ( breaks ) } ) if isinstance ( scale , scale_continuous ) : limits = scale . limits b = np . asarray ( breaks ) noob = np . logical_and ( limits [ 0 ] <= b , b <= limits [ 1 ] ) key = key [ noob ] if len ( key ) == 0 : return None self . key = key labels = ' ' . join ( str ( x ) for x in self . key [ 'label' ] ) info = '\n' . join ( [ self . title , labels , str ( self . direction ) , self . __class__ . __name__ ] ) self . hash = hashlib . md5 ( info . encode ( 'utf-8' ) ) . hexdigest ( ) return self
Create the key for the guide
25,646
def create_geoms ( self , plot ) : def get_legend_geom ( layer ) : if hasattr ( layer . geom , 'draw_legend' ) : geom = layer . geom . __class__ else : name = 'geom_{}' . format ( layer . geom . legend_geom ) geom = Registry [ name ] return geom self . glayers = [ ] for l in plot . layers : exclude = set ( ) if isinstance ( l . show_legend , dict ) : l . show_legend = rename_aesthetics ( l . show_legend ) exclude = { ae for ae , val in l . show_legend . items ( ) if not val } elif l . show_legend not in ( None , True ) : continue matched = self . legend_aesthetics ( l , plot ) if not set ( matched ) - exclude : continue data = self . key [ matched ] . copy ( ) data = l . use_defaults ( data ) for ae in set ( self . override_aes ) & set ( data . columns ) : data [ ae ] = self . override_aes [ ae ] geom = get_legend_geom ( l ) data = remove_missing ( data , l . geom . params [ 'na_rm' ] , list ( l . geom . REQUIRED_AES | l . geom . NON_MISSING_AES ) , '{} legend' . format ( l . geom . __class__ . __name__ ) ) self . glayers . append ( types . SimpleNamespace ( geom = geom , data = data , layer = l ) ) if not self . glayers : return None return self
Make information needed to draw a legend for each of the layers .
25,647
def get_package_data ( ) : baseline_images = [ 'tests/baseline_images/%s/*' % x for x in os . listdir ( 'plotnine/tests/baseline_images' ) ] csv_data = [ 'data/*.csv' ] package_data = { 'plotnine' : baseline_images + csv_data } return package_data
Return package data
25,648
def _get_all_imports ( ) : import types lst = [ name for name , obj in globals ( ) . items ( ) if not ( name . startswith ( '_' ) or name == 'absolute_import' or isinstance ( obj , types . ModuleType ) ) ] return lst
Return list of all the imports
25,649
def _rectangles_to_polygons ( df ) : n = len ( df ) xmin_idx = np . tile ( [ True , True , False , False ] , n ) xmax_idx = ~ xmin_idx ymin_idx = np . tile ( [ True , False , False , True ] , n ) ymax_idx = ~ ymin_idx x = np . empty ( n * 4 ) y = np . empty ( n * 4 ) x [ xmin_idx ] = df [ 'xmin' ] . repeat ( 2 ) x [ xmax_idx ] = df [ 'xmax' ] . repeat ( 2 ) y [ ymin_idx ] = df [ 'ymin' ] . repeat ( 2 ) y [ ymax_idx ] = df [ 'ymax' ] . repeat ( 2 ) other_cols = df . columns . difference ( [ 'x' , 'y' , 'xmin' , 'xmax' , 'ymin' , 'ymax' ] ) d = { col : np . repeat ( df [ col ] . values , 4 ) for col in other_cols } data = pd . DataFrame ( { 'x' : x , 'y' : y , ** d } ) return data
Convert rect data to polygons
25,650
def rename_aesthetics ( obj ) : if isinstance ( obj , dict ) : for name in obj : new_name = name . replace ( 'colour' , 'color' ) if name != new_name : obj [ new_name ] = obj . pop ( name ) else : obj = [ name . replace ( 'colour' , 'color' ) for name in obj ] return obj
Rename aesthetics in obj
25,651
def get_calculated_aes ( aesthetics ) : calculated_aesthetics = [ ] for name , value in aesthetics . items ( ) : if is_calculated_aes ( value ) : calculated_aesthetics . append ( name ) return calculated_aesthetics
Return a list of the aesthetics that are calculated
25,652
def is_calculated_aes ( ae ) : if not isinstance ( ae , str ) : return False for pattern in ( STAT_RE , DOTS_RE ) : if pattern . search ( ae ) : return True return False
Return a True if of the aesthetics that are calculated
25,653
def strip_stat ( value ) : def strip_hanging_closing_parens ( s ) : stack = 0 idx = [ ] for i , c in enumerate ( s ) : if c == '(' : stack += 1 elif c == ')' : stack -= 1 if stack < 0 : idx . append ( i ) stack = 0 continue yield c with suppress ( TypeError ) : if STAT_RE . search ( value ) : value = re . sub ( r'\bstat\(' , '' , value ) value = '' . join ( strip_hanging_closing_parens ( value ) ) return value
Remove calc function that mark calculated aesthetics
25,654
def is_position_aes ( vars_ ) : try : return all ( [ aes_to_scale ( v ) in { 'x' , 'y' } for v in vars_ ] ) except TypeError : return aes_to_scale ( vars_ ) in { 'x' , 'y' }
Figure out if an aesthetic is a position aesthetic or not
25,655
def make_labels ( mapping ) : labels = mapping . copy ( ) for ae in labels : labels [ ae ] = strip_calculated_markers ( labels [ ae ] ) return labels
Convert aesthetic mapping into text labels
25,656
def is_valid_aesthetic ( value , ae ) : if ae == 'linetype' : named = { 'solid' , 'dashed' , 'dashdot' , 'dotted' , '_' , '--' , '-.' , ':' , 'None' , ' ' , '' } if value in named : return True conditions = [ isinstance ( value , tuple ) , isinstance ( value [ 0 ] , int ) , isinstance ( value [ 1 ] , tuple ) , len ( value [ 1 ] ) % 2 == 0 , all ( isinstance ( x , int ) for x in value [ 1 ] ) ] if all ( conditions ) : return True return False elif ae == 'shape' : if isinstance ( value , str ) : return True conditions = [ isinstance ( value , tuple ) , all ( isinstance ( x , int ) for x in value ) , 0 <= value [ 1 ] < 3 ] if all ( conditions ) : return True return False elif ae in { 'color' , 'fill' } : if isinstance ( value , str ) : return True with suppress ( TypeError ) : if ( isinstance ( value , ( tuple , list ) ) and all ( 0 <= x <= 1 for x in value ) ) : return True return False return False
Return True if value looks valid .
25,657
def parse_wrap_facets ( facets ) : valid_forms = [ '~ var1' , '~ var1 + var2' ] error_msg = ( "Valid formula for 'facet_wrap' look like" " {}" . format ( valid_forms ) ) if isinstance ( facets , ( list , tuple ) ) : return facets if not isinstance ( facets , str ) : raise PlotnineError ( error_msg ) if '~' in facets : variables_pattern = r'(\w+(?:\s*\+\s*\w+)*|\.)' pattern = r'\s*~\s*{0}\s*' . format ( variables_pattern ) match = re . match ( pattern , facets ) if not match : raise PlotnineError ( error_msg ) facets = [ var . strip ( ) for var in match . group ( 1 ) . split ( '+' ) ] elif re . match ( r'\w+' , facets ) : facets = [ facets ] else : raise PlotnineError ( error_msg ) return facets
Return list of facetting variables
25,658
def n2mfrow ( nr_plots ) : if nr_plots <= 3 : nrow , ncol = nr_plots , 1 elif nr_plots <= 6 : nrow , ncol = ( nr_plots + 1 ) // 2 , 2 elif nr_plots <= 12 : nrow , ncol = ( nr_plots + 2 ) // 3 , 3 else : nrow = int ( np . ceil ( np . sqrt ( nr_plots ) ) ) ncol = int ( np . ceil ( nr_plots / nrow ) ) return ( nrow , ncol )
Compute the rows and columns given the number of plots .
25,659
def spaceout_and_resize_panels ( self ) : ncol = self . ncol nrow = self . nrow figure = self . figure theme = self . theme get_property = theme . themeables . property left = figure . subplotpars . left right = figure . subplotpars . right top = figure . subplotpars . top bottom = figure . subplotpars . bottom top_strip_height = self . strip_size ( 'top' ) W , H = figure . get_size_inches ( ) try : spacing_x = get_property ( 'panel_spacing_x' ) except KeyError : spacing_x = 0.1 try : spacing_y = get_property ( 'panel_spacing_y' ) except KeyError : spacing_y = 0.1 try : aspect_ratio = get_property ( 'aspect_ratio' ) except KeyError : if not self . free [ 'x' ] and not self . free [ 'y' ] : aspect_ratio = self . coordinates . aspect ( self . layout . panel_params [ 0 ] ) else : aspect_ratio = None if theme . themeables . is_blank ( 'strip_text_x' ) : top_strip_height = 0 with suppress ( KeyError ) : strip_margin_x = get_property ( 'strip_margin_x' ) top_strip_height *= ( 1 + strip_margin_x ) w = ( ( right - left ) * W - spacing_x * ( ncol - 1 ) ) / ncol h = ( ( top - bottom ) * H - ( spacing_y + top_strip_height ) * ( nrow - 1 ) ) / nrow if aspect_ratio is not None : h = w * aspect_ratio H = ( h * nrow + ( spacing_y + top_strip_height ) * ( nrow - 1 ) ) / ( top - bottom ) figure . set_figheight ( H ) wspace = spacing_x / w hspace = ( spacing_y + top_strip_height ) / h figure . subplots_adjust ( wspace = wspace , hspace = hspace )
Adjust the spacing between the panels and resize them to meet the aspect ratio
25,660
def get_as ( self , key , units = 'pt' ) : dpi = 72 size = self . element . properties . get ( 'size' , 0 ) value = self [ key ] functions = { 'pt-lines' : lambda x : x / size , 'pt-in' : lambda x : x / dpi , 'lines-pt' : lambda x : x * size , 'lines-in' : lambda x : x * size / dpi , 'in-pt' : lambda x : x * dpi , 'in-lines' : lambda x : x * dpi / size } if self [ 'units' ] != units : conversion = '{}-{}' . format ( self [ 'units' ] , units ) try : value = functions [ conversion ] ( value ) except ZeroDivisionError : value = 0 return value
Return key in given units
25,661
def discrete_columns ( df , ignore ) : lst = [ ] for col in df : if array_kind . discrete ( df [ col ] ) and ( col not in ignore ) : try : hash ( df [ col ] . iloc [ 0 ] ) except TypeError : continue lst . append ( col ) return lst
Return a list of the discrete columns in the dataframe df . ignore is a list|set|tuple with the names of the columns to skip .
25,662
def is_known_scalar ( value ) : def _is_datetime_or_timedelta ( value ) : return pd . Series ( value ) . dtype . kind in ( 'M' , 'm' ) return not np . iterable ( value ) and ( isinstance ( value , numbers . Number ) or _is_datetime_or_timedelta ( value ) )
Return True if value is a type we expect in a dataframe
25,663
def generate_data ( self , plot_data ) : if self . data is None : self . data = plot_data . copy ( ) elif hasattr ( self . data , '__call__' ) : self . data = self . data ( plot_data ) if not isinstance ( self . data , pd . DataFrame ) : raise PlotnineError ( "Data function must return a dataframe" ) else : self . data = self . data . copy ( )
Generate data to be used by this layer
25,664
def layer_mapping ( self , mapping ) : if self . inherit_aes : aesthetics = defaults ( self . mapping , mapping ) else : aesthetics = self . mapping calculated = set ( get_calculated_aes ( aesthetics ) ) d = dict ( ( ae , v ) for ae , v in aesthetics . items ( ) if ( ae not in self . geom . aes_params ) and ( ae not in calculated ) ) self . _active_mapping = aes ( ** d ) return self . _active_mapping
Return the mappings that are active in this layer
25,665
def compute_aesthetics ( self , plot ) : data = self . data aesthetics = self . layer_mapping ( plot . mapping ) with suppress ( KeyError ) : aesthetics [ 'group' ] = self . geom . aes_params [ 'group' ] env = EvalEnvironment . capture ( eval_env = plot . environment ) env = env . with_outer_namespace ( { 'factor' : pd . Categorical } ) evaled = type ( data ) ( index = data . index ) for ae , col in aesthetics . items ( ) : if isinstance ( col , str ) : if col in data : evaled [ ae ] = data [ col ] else : try : new_val = env . eval ( col , inner_namespace = data ) except Exception as e : raise PlotnineError ( _TPL_EVAL_FAIL . format ( ae , col , str ( e ) ) ) try : evaled [ ae ] = new_val except Exception as e : raise PlotnineError ( _TPL_BAD_EVAL_TYPE . format ( ae , col , str ( type ( new_val ) ) , str ( e ) ) ) elif pdtypes . is_list_like ( col ) : n = len ( col ) if len ( data ) and n != len ( data ) and n != 1 : raise PlotnineError ( "Aesthetics must either be length one, " + "or the same length as the data" ) elif len ( evaled ) and n == 1 : col = col [ 0 ] evaled [ ae ] = col elif is_known_scalar ( col ) : if not len ( evaled ) : col = [ col ] evaled [ ae ] = col else : msg = "Do not know how to deal with aesthetic '{}'" raise PlotnineError ( msg . format ( ae ) ) evaled_aes = aes ( ** dict ( ( col , col ) for col in evaled ) ) plot . scales . add_defaults ( evaled , evaled_aes ) if len ( data ) == 0 and len ( evaled ) > 0 : evaled [ 'PANEL' ] = 1 else : evaled [ 'PANEL' ] = data [ 'PANEL' ] self . data = add_group ( evaled )
Return a dataframe where the columns match the aesthetic mappings .
25,666
def compute_statistic ( self , layout ) : data = self . data if not len ( data ) : return type ( data ) ( ) params = self . stat . setup_params ( data ) data = self . stat . use_defaults ( data ) data = self . stat . setup_data ( data ) data = self . stat . compute_layer ( data , params , layout ) self . data = data
Compute & return statistics for this layer
25,667
def map_statistic ( self , plot ) : data = self . data if not len ( data ) : return type ( data ) ( ) aesthetics = deepcopy ( self . mapping ) if self . inherit_aes : aesthetics = defaults ( aesthetics , plot . mapping ) aesthetics = defaults ( aesthetics , self . stat . DEFAULT_AES ) new = { } stat_data = type ( data ) ( ) stat_namespace = dict ( stat = stat ) env = plot . environment . with_outer_namespace ( stat_namespace ) for ae in get_calculated_aes ( aesthetics ) : new [ ae ] = strip_calculated_markers ( aesthetics [ ae ] ) if new [ ae ] != ae : stat_data [ ae ] = env . eval ( new [ ae ] , inner_namespace = data ) if not new : return if self . stat . retransform : stat_data = plot . scales . transform_df ( stat_data ) columns = data . columns . difference ( stat_data . columns ) self . data = pd . concat ( [ data [ columns ] , stat_data ] , axis = 1 ) plot . scales . add_defaults ( self . data , new )
Mapping aesthetics to computed statistics
25,668
def compute_position ( self , layout ) : params = self . position . setup_params ( self . data ) data = self . position . setup_data ( self . data , params ) data = self . position . compute_layer ( data , params , layout ) self . data = data
Compute the position of each geometric object in concert with the other objects in the panel
25,669
def train ( self , x ) : self . range = scale_continuous . train ( x , self . range )
Train continuous range
25,670
def train ( self , x , drop = False , na_rm = False ) : self . range = scale_discrete . train ( x , self . range , drop , na_rm = na_rm )
Train discrete range
25,671
def _margins ( vars , margins = True ) : if margins is False : return [ ] def fn ( _vars ) : "The margin variables for a given row or column" dim_margins = [ [ ] ] for i , u in enumerate ( _vars ) : if margins is True or u in margins : lst = [ u ] + [ v for v in _vars [ i + 1 : ] ] dim_margins . append ( lst ) return dim_margins row_margins = fn ( vars [ 0 ] ) col_margins = fn ( vars [ 1 ] ) lst = list ( itertools . product ( col_margins , row_margins ) ) pretty = [ ] for c , r in lst : pretty . append ( r + c ) return pretty
Figure out margining variables .
25,672
def add_margins ( df , vars , margins = True ) : margin_vars = _margins ( vars , margins ) if not margin_vars : return df margin_dfs = [ df ] for vlst in margin_vars [ 1 : ] : dfx = df . copy ( ) for v in vlst : dfx . loc [ 0 : , v ] = '(all)' margin_dfs . append ( dfx ) merged = pd . concat ( margin_dfs , axis = 0 ) merged . reset_index ( drop = True , inplace = True ) categories = { } for v in itertools . chain ( * vars ) : col = df [ v ] if not pdtypes . is_categorical_dtype ( df [ v ] . dtype ) : col = pd . Categorical ( df [ v ] ) categories [ v ] = col . categories if '(all)' not in categories [ v ] : categories [ v ] = categories [ v ] . insert ( len ( categories [ v ] ) , '(all)' ) for v in merged . columns . intersection ( set ( categories ) ) : merged [ v ] = merged [ v ] . astype ( pdtypes . CategoricalDtype ( categories [ v ] ) ) return merged
Add margins to a data frame .
25,673
def _id_var ( x , drop = False ) : if len ( x ) == 0 : return [ ] categorical = pdtypes . is_categorical_dtype ( x ) if categorical : if drop : x = x . cat . remove_unused_categories ( ) lst = list ( x . cat . codes + 1 ) else : has_nan = any ( np . isnan ( i ) for i in x if isinstance ( i , float ) ) if has_nan : nan_code = - 1 new_nan_code = np . max ( x . cat . codes ) + 1 lst = [ val if val != nan_code else new_nan_code for val in x ] else : lst = list ( x . cat . codes + 1 ) else : try : levels = np . sort ( np . unique ( x ) ) except TypeError : levels = multitype_sort ( set ( x ) ) lst = match ( x , levels ) lst = [ item + 1 for item in lst ] return lst
Assign ids to items in x . If two items are the same they get the same id .
25,674
def join_keys ( x , y , by = None ) : if by is None : by = slice ( None , None , None ) if isinstance ( by , tuple ) : by = list ( by ) joint = x [ by ] . append ( y [ by ] , ignore_index = True ) keys = ninteraction ( joint , drop = True ) keys = np . asarray ( keys ) nx , ny = len ( x ) , len ( y ) return { 'x' : keys [ np . arange ( nx ) ] , 'y' : keys [ nx + np . arange ( ny ) ] }
Join keys .
25,675
def uniquecols ( df ) : bool_idx = df . apply ( lambda col : len ( np . unique ( col ) ) == 1 , axis = 0 ) df = df . loc [ : , bool_idx ] . iloc [ 0 : 1 , : ] . reset_index ( drop = True ) return df
Return unique columns
25,676
def defaults ( d1 , d2 ) : d1 = d1 . copy ( ) tolist = isinstance ( d2 , pd . DataFrame ) keys = ( k for k in d2 if k not in d1 ) for k in keys : if tolist : d1 [ k ] = d2 [ k ] . tolist ( ) else : d1 [ k ] = d2 [ k ] return d1
Update a copy of d1 with the contents of d2 that are not in d1 . d1 and d2 are dictionary like objects .
25,677
def jitter ( x , factor = 1 , amount = None , random_state = None ) : if len ( x ) == 0 : return x if random_state is None : random_state = np . random elif isinstance ( random_state , int ) : random_state = np . random . RandomState ( random_state ) x = np . asarray ( x ) try : z = np . ptp ( x [ np . isfinite ( x ) ] ) except IndexError : z = 0 if z == 0 : z = np . abs ( np . min ( x ) ) if z == 0 : z = 1 if amount is None : _x = np . round ( x , 3 - np . int ( np . floor ( np . log10 ( z ) ) ) ) . astype ( np . int ) xx = np . unique ( np . sort ( _x ) ) d = np . diff ( xx ) if len ( d ) : d = d . min ( ) elif xx != 0 : d = xx / 10. else : d = z / 10 amount = factor / 5. * abs ( d ) elif amount == 0 : amount = factor * ( z / 50. ) return x + random_state . uniform ( - amount , amount , len ( x ) )
Add a small amount of noise to values in an array_like
25,678
def remove_missing ( df , na_rm = False , vars = None , name = '' , finite = False ) : n = len ( df ) if vars is None : vars = df . columns else : vars = df . columns . intersection ( vars ) if finite : lst = [ np . inf , - np . inf ] to_replace = { v : lst for v in vars } df . replace ( to_replace , np . nan , inplace = True ) txt = 'non-finite' else : txt = 'missing' df = df . dropna ( subset = vars ) df . reset_index ( drop = True , inplace = True ) if len ( df ) < n and not na_rm : msg = '{} : Removed {} rows containing {} values.' warn ( msg . format ( name , n - len ( df ) , txt ) , PlotnineWarning , stacklevel = 3 ) return df
Convenience function to remove missing values from a dataframe
25,679
def to_rgba ( colors , alpha ) : def is_iterable ( var ) : return cbook . iterable ( var ) and not is_string ( var ) def has_alpha ( c ) : if isinstance ( c , tuple ) : if len ( c ) == 4 : return True elif isinstance ( c , str ) : if c [ 0 ] == '#' and len ( c ) == 9 : return True return False def no_color ( c ) : return c is None or c == '' or c . lower ( ) == 'none' def to_rgba_hex ( c , a ) : _has_alpha = has_alpha ( c ) c = mcolors . to_hex ( c , keep_alpha = _has_alpha ) if not _has_alpha : arr = colorConverter . to_rgba ( c , a ) return mcolors . to_hex ( arr , keep_alpha = True ) return c if is_iterable ( colors ) : if all ( no_color ( c ) for c in colors ) : return 'none' if is_iterable ( alpha ) : return [ to_rgba_hex ( c , a ) for c , a in zip ( colors , alpha ) ] else : return [ to_rgba_hex ( c , alpha ) for c in colors ] else : if no_color ( colors ) : return colors if is_iterable ( alpha ) : return [ to_rgba_hex ( colors , a ) for a in alpha ] else : return to_rgba_hex ( colors , alpha )
Covert hex colors to rgba values .
25,680
def groupby_apply ( df , cols , func , * args , ** kwargs ) : try : axis = kwargs . pop ( 'axis' ) except KeyError : axis = 0 lst = [ ] for _ , d in df . groupby ( cols ) : lst . append ( func ( d , * args , ** kwargs ) ) return pd . concat ( lst , axis = axis , ignore_index = True )
Groupby cols and call the function fn on each grouped dataframe .
25,681
def pivot_apply ( df , column , index , func , * args , ** kwargs ) : def _func ( x ) : return func ( x , * args , ** kwargs ) return df . pivot_table ( column , index , aggfunc = _func ) [ column ]
Apply a function to each group of a column
25,682
def copy_keys ( source , destination , keys = None ) : if keys is None : keys = destination . keys ( ) for k in set ( source ) & set ( keys ) : destination [ k ] = source [ k ] return destination
Add keys in source to destination
25,683
def alias ( name , class_object ) : module = inspect . getmodule ( class_object ) module . __dict__ [ name ] = class_object if isinstance ( class_object , Registry ) : Registry [ name ] = class_object
Create an alias of a class object
25,684
def get_kwarg_names ( func ) : sig = inspect . signature ( func ) kwonlyargs = [ p . name for p in sig . parameters . values ( ) if p . default is not p . empty ] return kwonlyargs
Return a list of valid kwargs to function func
25,685
def get_valid_kwargs ( func , potential_kwargs ) : kwargs = { } for name in get_kwarg_names ( func ) : with suppress ( KeyError ) : kwargs [ name ] = potential_kwargs [ name ] return kwargs
Return valid kwargs to function func
25,686
def copy_missing_columns ( df , ref_df ) : cols = ref_df . columns . difference ( df . columns ) _loc = ref_df . columns . get_loc l1 , l2 = len ( df ) , len ( ref_df ) if l1 >= l2 and l1 % l2 == 0 : idx = np . tile ( range ( l2 ) , l1 // l2 ) else : idx = np . repeat ( 0 , l1 ) for col in cols : df [ col ] = ref_df . iloc [ idx , _loc ( col ) ] . values
Copy missing columns from ref_df to df
25,687
def data_mapping_as_kwargs ( args , kwargs ) : aes = dict mapping , data = aes ( ) , None aes_err = ( "Found more than one aes argument. " "Expecting zero or one" ) data_err = "More than one dataframe argument." for arg in args : if isinstance ( arg , aes ) and mapping : raise PlotnineError ( aes_err ) if isinstance ( arg , pd . DataFrame ) and data : raise PlotnineError ( data_err ) if isinstance ( arg , aes ) : mapping = arg elif isinstance ( arg , pd . DataFrame ) : data = arg else : msg = "Unknown argument of type '{0}'." raise PlotnineError ( msg . format ( type ( arg ) ) ) if 'mapping' not in kwargs : kwargs [ 'mapping' ] = mapping if data is not None and 'data' in kwargs : raise PlotnineError ( data_err ) elif 'data' not in kwargs : kwargs [ 'data' ] = data duplicates = set ( kwargs [ 'mapping' ] ) & set ( kwargs ) if duplicates : msg = "Aesthetics {} specified two times." raise PlotnineError ( msg . format ( duplicates ) ) return kwargs
Return kwargs with the mapping and data values
25,688
def resolution ( x , zero = True ) : x = np . asarray ( x ) _x = x [ ~ np . isnan ( x ) ] _x = ( x . min ( ) , x . max ( ) ) if x . dtype . kind in ( 'i' , 'u' ) or zero_range ( _x ) : return 1 x = np . unique ( x ) if zero : x = np . unique ( np . hstack ( [ 0 , x ] ) ) return np . min ( np . diff ( np . sort ( x ) ) )
Compute the resolution of a data vector
25,689
def cross_join ( df1 , df2 ) : if len ( df1 ) == 0 : return df2 if len ( df2 ) == 0 : return df1 all_columns = pd . Index ( list ( df1 . columns ) + list ( df2 . columns ) ) df1 [ 'key' ] = 1 df2 [ 'key' ] = 1 return pd . merge ( df1 , df2 , on = 'key' ) . loc [ : , all_columns ]
Return a dataframe that is a cross between dataframes df1 and df2
25,690
def to_inches ( value , units ) : lookup = { 'in' : lambda x : x , 'cm' : lambda x : x / 2.54 , 'mm' : lambda x : x / ( 2.54 * 10 ) } try : return lookup [ units ] ( value ) except KeyError : raise PlotnineError ( "Unknown units '{}'" . format ( units ) )
Convert value to inches
25,691
def from_inches ( value , units ) : lookup = { 'in' : lambda x : x , 'cm' : lambda x : x * 2.54 , 'mm' : lambda x : x * 2.54 * 10 } try : return lookup [ units ] ( value ) except KeyError : raise PlotnineError ( "Unknown units '{}'" . format ( units ) )
Convert value in inches to given units
25,692
def log ( x , base = None ) : if base == 10 : return np . log10 ( x ) elif base == 2 : return np . log2 ( x ) elif base is None or base == np . e : return np . log ( x ) else : return np . log ( x ) / np . log ( base )
Calculate the log
25,693
def handle ( cls , value , context , ** kwargs ) : try : hook_name , key = value . split ( "::" ) except ValueError : raise ValueError ( "Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value ) return context . hook_data [ hook_name ] [ key ]
Returns the value of a key for a given hook in hook_data .
25,694
def resolve_variables ( variables , context , provider ) : for variable in variables : variable . resolve ( context , provider )
Given a list of variables resolve all of them .
25,695
def value ( self ) : try : return self . _value . value ( ) except UnresolvedVariableValue : raise UnresolvedVariable ( "<unknown>" , self ) except InvalidLookupConcatenation as e : raise InvalidLookupCombination ( e . lookup , e . lookups , self )
Return the current value of the Variable .
25,696
def resolve ( self , context , provider ) : try : self . _value . resolve ( context , provider ) except FailedLookup as e : raise FailedVariableLookup ( self . name , e . lookup , e . error )
Recursively resolve any lookups with the Variable .
25,697
def run ( self ) : stop_watcher = threading . Event ( ) watcher = None if self . watch_func : watcher = threading . Thread ( target = self . watch_func , args = ( self . stack , stop_watcher ) ) watcher . start ( ) try : while not self . done : self . _run_once ( ) finally : if watcher : stop_watcher . set ( ) watcher . join ( ) return self . ok
Runs this step until it has completed successfully or been skipped .
25,698
def downstream ( self , step_name ) : return list ( self . steps [ dep ] for dep in self . dag . downstream ( step_name ) )
Returns the direct dependencies of the given step
25,699
def transposed ( self ) : return Graph ( steps = self . steps , dag = self . dag . transpose ( ) )
Returns a transposed version of this graph . Useful for walking in reverse .