DataDraw function reference

    DataDraw user-callable functions.  

    
    Usage:  pip install datadraw

            from datadraw import DataDraw 

            dd = DataDraw(logmsg=True)
            dd.svgbegin(width=400, height=300, testpat=True)
            mysvg = dd.svgresult()

    Most drawing and rendering functions generate SVG code to an internal buffer.
    The user accesses it using svgresult() and then typically includes the SVG in 
    an html page.

    Native coordinate system ('native units') is SVG units (usually 1/72") with 
    origin in the lower-left of the rendered graphic.  See test pattern in 
    example set 1 for illustration.

    In these function descriptions, args that are always required are shown in
    the green section.  All other args are optional (subject to any usage rules 
    given in the description).  Required args sometimes have keywords to help
    with caller code readability.  Some functions have a return value but most
    do not.  'Google docstring format' is used here.  Recent changes / additions
    are denoted with a version number eg. '(new in 0.7.2)'.

    To see your DataDraw version, use logmsg=True as above; a startup message 
    is written to console.  If the message has no version ID then it's  0.7.1

    DataDraw codebase is released under the MIT License.
    Documentation (c) 2024 Steve Grubb




Section 1. Starting and ending



    svgbegin( width=None, height=None,  ...  )

        Begin a new graphic.  Initialize a new SVG code buffer.
        Typical example:  svgbegin(width=400, height=300)
        Args:  
            width (int):    width of graphic in native units
            height (int):   height of graphic in native units
            bgcolor (str):  background fill color; defaults to '#fff'
            svgtag (str):   customized svg opening tag content
            outline (bool): if True outline the graphic 
            rounded:        if True (or list[2]) round the corners; see rect() 
            testpat (bool): if True render a test pattern in the graphic area.


    svgresult(  ...  )

        Get contents of your SVG code buffer.  Includes closing /svg tag by default.
        Typical example:  mysvg = svgresult() ... then include mysvg in an html page.
        Args:
            tofile (str, pathname): write svg buffer to this file.  See 
                                    write_svgfile() for usage caveats.
            noclose (bool):         if True don't include closing /svg tag
        Returns:
            str: your SVG code generated thus far


    svgappend( svgcode  )

        Append an arbitrary string to your SVG code buffer.
        Could be used for aspects not covered by this function library.
        Args:
            svgcode (str):  some svg code to append



Section 2. Controlling various settings



    setline(  ...  )

        Control various line rendering settings for subsequent drawing.  
        Each individual setting remains in effect until explicitly changed.
        Typical example:  setline(color='#a77', width=2.0, dash=[8,4])
        Args: 
            width (float):   line width; defaults to 1.0
            color (str):     line color; defaults to '#000'
            opacity (float): line opacity; defaults to 1.0 (opaque); 0.0 == fully transparent.
            dash (list):     controls line dashing; an svg stroke-dasharray value eg. [8,3]
            css (str):       css class name(s) to influence line rendering
            style (str):     css style value to influence line rendering
          Args that are special actions:
            save (bool):     if True remember all current settings for future 'restore'
            restore (bool):  if True load most recent 'save' settings 
            reset (bool):    if True all settings revert to initial state.
            With reset=True or restore=True any other args are ignored.
            With save=True other args can be present too (and are remembered).
            If no save has ever been done, restore=True is same as reset=True.


    settext(  ...  )

        Control various text rendering settings.  
        Each individual setting remains in effect until explicitly changed.
        Typical example:  settext(ptsize=12, color='#777', anchor='middle')
        Args:  
            ptsize (int):          text point size; defaults to 10
            color (str):           text color; defaults to '#000'
            anchor (str):          one of ['start', 'middle', 'end']; defaults to 'start'
            rotate (int, degrees): text direction; defaults to 0 (horizontal).  Try 90, -90, etc.
            adjust (list[2]):      adjust text locations by [x, y] in native units.
            The opacity, css, style, reset, save, and restore args are same as in setline()


    setdt(  ...  )

        Control various datetime settings.  
        Each individual setting remains in effect until explicitly changed.
        Typical example:  setdt(dtformat='%m/%d/%Y')
        See also the datetime conversion functions in Section 10.
        Args:  
            dtformat (str):  format for data parsing and display; defaults to '%Y-%m-%d'
              See also: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
              ('zero-padded' applies to display only; parsing handles eg. '3/4/2024')
            weekday0 (int):  weekday to use for 'week' boundary; defaults to 0 == Monday
            fymonth1 (int):  month to use for fiscal year boundary; defaults to 1 == January


    setclustering( mode='surround',  ...  )

        Control datapoint() clustering settings for scatterplots, histograms, etc.
        Each individual setting remains in effect until explicitly changed.
          Data should be sorted on (x, y).  The most recently-rendered data point location 
        is remembered.  If the next-rendered data point coincides, clustering causes it 
        to be slightly displaced automatically, to convey multiplicity or to 'stack' for 
        ie. histograms (or with mode='omit_dups' simply omitted to cut down on SVG bulk).  
          When mode='surround' the displacement is a randomized jitter; for other modes 
        the displacement is the value of the offset arg.  See example sets 4 and 5 for 
        some usage ideas.
        Args: 
            mode (str):     type of clustering; defaults to 'surround'.  One of 
                            ['surround', 'omit_dups', 'left+right', 'rightward', 'leftward', 
                            'up+down', 'upward', 'downward'].  None == turn off clustering.
            offset (float): distance to displace coinciding data point location in native 
                            units; defaults to 1.0.
            tolerance (float): indicates how close (in native units) two data points 
                            must be, to be considered "coinciding"; defaults to 0.0
            jitter (float): add some randomization to displacement amount; defaults to 0.5
                            when mode='surround', 0.0 otherwise.
            dampen (int):   tame clustering effect when many coinciding points; defaults to 1;
                            a value of eg. 5 treats 5 coinciding points as just 1.
            conform (bool): if True suppress a 'teetering' artifact that may occur (True).


    set_misc(  ...  )

        Control other miscellaneous settings.
        Args:
            crossorigin (str): related to image() and CORS issues, see
              https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/crossorigin



Section 3. Getting summary info on your data

    Numeric min max range, list of categories, summary stats, distributions etc. 


    findrange( value  )

        Check a data value to find data's min, max range.  Typically called 
        multiple times while interating over plottable data values.  User 
        then calls findrange_result() to get the final min and max.  
          For datetime data, use intdt() on each datetime string beforehand, 
        to convert it to a numeric.
        Args:
            value (float):  examined numeric value


    findrange_result(  ...  )

        After calls to findrange(), report the observed data min and max, 
        as well as adjusted min and max for 'nice' axis purposes.  Some other 
        metrics are also included.
        Args: 
            nearest: influence the determination of 'nice axis' min and max.
                       For numeric data this arg is optional; it will use a 
                     reasonable default.  Otherwise specify a number, eg. 50 
                     would adjust the min and max outward to the closest multiple 
                     of 50.  
                       For datetime data this arg is required; specify one of: 
                     ['year', '3month', 'month', 'week', 'day', 'hour', 'minute', 
                     '12hour', '6hour', '4hour', '3hour', '30minute', '10minute'];
                     the returned elements dt_axmin and dt_axmax will be at the 
                     closest requested boundary, in your current datetime format.
        Returns:
            dict: having this numeric info: the 'final' range for nice axis purposes
                  ('axmin', 'axmax'); the raw min and max ('datamin', 'datamax'); 
                  a default axis increment value ('inc'); number of usable values ('nvals') 
                  number of non-numerics seen ('nbadvals'). Also booleans: are all data 
                  integer? ('allint'); are all positive? ('allpos'); all negative? ('allneg').
                    With datetime data the similar following are also available as str 
                  in the current datetime format: 'dt_axmin', 'dt_axmax', 'dt_inc',
                  'dt_datamin', 'dt_datamax'


    catinfo( datarows, column,  ...  )

        Get info on your categorical data ie. a dict of categorical values seen with
        occurrence counts.  This dict can then be used to render a categorical axis.
        If an error is raised when getting the requested column from datarows, a
        data value of None is used.
        Args:
            datarows: data to iterate over, either a list of dict, or a list of tuple,
                      or just a 1-D list.
            column:   data column to examine.  If datarows is a list of tuple this
                      is an integer starting with 0; otherwise if datarows is a 
                      list of dict this is a string naming a dict element.
                      If datarows is a simple list just use None.
            accumcol: if specified, instead of counting occurrences as 1 each,
                      this column's contents are summed.  Same rules as above.
            nulls:    how to handle None data values.  Default is to 'ignore'.
                      Use 'spacers' to cause each None to add a dummy entry to the
                      returned dict which axis drawing will interpret as a spacer 
                      or separator, a sometimes-useful feature.
        Returns:
            dict:  a dict of observed values (in the order seen) with counts


    numinfo( datarows, column,  ...  )

        Get basic stats (and optionally distribution-centric info) on your numeric data.
        If an error is raised when getting the requested column from datarows, a
        data value of None is used.
        Args:
            The datarows, column, and accumcol args operate same as in catinfo().
            find_distrib (bool):     if True compute a frequency distribution
            binsize (float):         bin size for numeric frequency distribution; if not 
                                     specified a reasonable default is used.
            find_percentiles (bool): if True compute percentiles eg. for box plots
        Returns:
            dict:  having this info: data range ('min', 'max'); number of usable
                   values ('nvals') and non-numeric or None values seen ('nbadvals');
                   mean, SD, SEM, and sum ('mean', 'sd', 'sem', 'sum').  Also 
                   booleans: are all usable data int ('allint'); are all usable data 
                   in order ('numsorted').
                     If find_distrib=True then the 'distribution' and 'distbinsize' 
                   elements are populated.  If find_percentiles=True then the 
                   'percentiles' element will be populated.



Section 4. Basic drawing using native coordinates



    lin( x1, y1, x2, y2,  ...  )

        Draw a line from x1,y1 to x2,y2 using current line settings.
        Args:
            x1, y1 (float): starting point in native coords.
            x2, y2 (float): ending point in native coords.
            svgstr (str):   optional inline code to add to SVG  statement


    txt( x, y, txt,  ...  )

        Render text at x,y using current text settings.  Some temp setting overrides 
        (in play only during this function call) are available.
        Args:
            x, y (float): location to render text in native coords
            txt (str):    text string.  Can contain utf-8, HTML char constructs,
                          and DataDraw-implemented newline ('\n'), superscript
                          ('' and '') and subscript ('')
                          operators.
            anchor, adjust, rotate: temp setting overrides, see settext()
            svgstr (str): optional inline code to add to SVG  statement


    rect( x1, y1, x2, y2,  ...  )

        Render a rectangle.
        Args:
            x1, y1 (float):  location of lower left in native coords
            x2, y2 (float):  location of upper right in native coords
            color (str):     fill color; defaults to '#ddd'; None == no fill
            opacity (float): opacity of fill; defaults to 1.0 (opaque); 0.0 == transparent.
            outline (bool):  if True outline the rect using current line settings
            rounded:         if True round the corners using rx=12, ry=12.  Or specify as 
                             list[2] to round using your 2 explicit values.


    polygon( ptlist,  ...  )

        Render a polygon from a list of (x, y) tuples.
        Args:
            ptlist (list):   a list of (x, y) tuples in native units.
            color (str):     fill color; defaults to '#aaa'; None == no fill
            opacity (float): opacity of fill; defaults to 1.0 (opaque); 0.0 == transparent.
            outline (bool):  if True outline the rect using current line settings


    circle( x, y, diameter,  ...  )

        Render a circle.
        Args:
            x, y (float):     circle centered around this point in native units
            diameter (float): diameter in native units
            color (str):      fill color; defaults to '#ddd'; None == no fill
            opacity (float):  opacity of fill; defaults to 1.0 (opaque); 0.0 == transparent.
            outline (bool):   if True outline the rect using current line settings


    ellipse( x, y,  ...  )

        Render an ellipse.
        Args:
            x, y (float):          ellipse centered around this point in native units
            width, height (float): width and height of ellipse in native units
            other args are same as circle()


    pieslice( pctval=None, startval=0.0,  ...  )

        Render one pie graph slice.  Called multiple times to render complete pie graph.
        Pie graph will be round and will fully occupy current rectangular graphic area, 
        abutting either the right or left side (placement).  See example set 1 for pattern.
        Args:
            pctval (float):   0.0 to 1.0; controls size of slice (1.0 == entire pie)
            startval (float): 0.0 to 1.0; position of slice; values > 1.0 wrap (fmod).
                              0.0 is straight up. 
            color (str):      fill color of the slice; defaults to '#ccc'
            outline (bool):   if True, outline the slice using current line settings
            opacity (float):  defaults to 1.0 (opaque)
            placement (str):  either 'right' or 'left'; which side of rectangular 
                              svg graphic area to abutt.
            showpct (bool):   if True, the pctval will be displayed as a % value


    image( href, x, y,  ...  )

        Render a JPG, PNG, GIF image.
        See also: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image
        Args:
            href (str):            url of the image file
            x, y (float):          placement of image upper-left in native coords
            width, height (float): explicit control of rendered size
            opacity (float):       defaults to 1.0 (opaque); 0.0 == transparent.
            par (bool):            preserve aspect ratio (see above url); defaults to True



Section 5: Tooltips, clickable linkouts



    gtag( mode,  ...  )

        Associate a popup tooltip or html clickable linkout with drawn graphics 
        element(s).  Based on the svg 'g' tag.  
          To use, call gtag('begin'...), then render some graphics, then call 
        gtag('end').  The tooltip or linkout will be activated when user hovers 
        their mouse over those graphics.  Extra gtag('end') calls are harmless.
        Args: 
            mode (str):    either 'begin' or 'end'
            Any of the following can be used with 'begin':
              tooltip (str): text to display as a popup tooltip.  Can include '\n'
              astring (str): construct for an 'a href' clickable linkout, for example:
                             astring='href="http://abc.com" target="_blank"'
              gstring (str): svg code to add into the 'g' element for CSS uses, etc.



Section 6: Creating data-scaled plotting space; and axis rendering

    Usual pattern is to call setspace() once for X then again for Y at an 
    early stage, then proceed with axes rendering, axes labels, and then 
    data-scaled plotting using the functions in Section 7.


    setspace( axis, svgrange=None,  ...  )

        Set up data-scaled plotting space in X or Y.  This associates your data,
        (either its numeric range or its categorical values), to a specific area in 
        your svg graphic.
          The svgrange arg is always required. In addition either datarange or 
        categorical must be supplied.  
        Typical numeric example:  setspace('Y', svgrange=(80, 420), datarange=(0.0, 1.0) )
        Args:   
            axis (str):     either 'X' or 'Y'
            svgrange:       tuple of (min, max) in native units*
            datarange:      numeric tuple of (min, max)*; if specified, scaling will be 
                            numeric.  For datetime ranges, use intdt() on each datetime 
                            string beforehand (scaling is still considered to be numeric).
            categorical:    list of category names*; scaling will be categorical.
            log (str):      one of ['log', 'log+1']; initiates logarithmic scaling
            reverse (bool): if True the sense of the scaling is reversed ie. high to low
            allint (bool):  if True the data are all integer; a hint for certain nuances

            *these args can sometimes be passed as dict: 
              svgrange: with 'poslo' and 'poshi' elements, when doing multipanel displays
              datarange: with 'axmin' and 'axmax' elements, when using findrange_result()
              categorical: can be a dict keyed on category names 


    axis( ax,  ...  )

        Render an axis scale in X or Y, in a data-scaled space (numeric or
        categorical).  To get a datetime-centric axis call datestubs() beforehand.
        There are many optional args for fine-tuning, try the defaults first.
        Typical example:  axis('Y', grid=True)
        Args:
            ax:               either 'X' or 'Y'
            axisline (bool):  if True render an axis line (defaults to True)
            inc (float):      axis increment.  Defaults to something reasonable.
            tics (int):       draw tics to this length in native units
            stubs (bool):     if True render stubs (the text next to each tic) (True)
            grid (bool):      if True render grid lines at tic locations (False)
            loc (str):        location of axis; defaults to 'bottom' for X and 'left' for Y;
                              also: 'top', 'right', or native unit constructs eg. 'left-30'
            stubformat (str): for numeric space eg. '.0f', '%g', '.4f', ',.0f' etc.
                              or for categorical eg. '%s', '%.10s'. The leading '%' is 
                              optional.  Defaults to a reasonable format string.
            comma000 (bool):  if True display larger numbers w/ comma separators; same as
                              stubformat=',.0f' but for convenience.  Defaults to False.  
            divideby (float): divide by this number to get the displayed numeric value
            stubcull (int):   avoid colliding stubs, esp. with log scale.  Any stub nearer
                              to its neighbor than this distance in native units is omitted.
            stublist (list):  supply a customized set of stubs to be placed at data-scale
                              numeric locations.  They can be regularly or irregularly 
                              spaced.  Either a list of numeric values, or a list of 
                              (value, label) tuples.
            stubrotate (int): rotate stubs by this many degrees (0 = horizontal)
            stubrange:        numeric tuple (min, max); omit stubs outside this range 
            stubadjust, stubanchor:  temp overrides for adjust, anchor; see settext()
            dateconvert:      specialized use to control format of categorical datetime 
                              values; a tuple of two datetime format strings (from, to)
            stubtemplate (str): Allows other text to accompany each stub.  The already-
                              formatted stub value is substituted at %s . (new in 0.7.2)
            templatemode (str): One of ['drawn', 'tooltip', 'both'].  If 'drawn' then 
                              stubtemplate is applied to the drawn stubs only; this is the
                              default.  If 'tooltip' then make tooltips on each stub based 
                              on stubtemplate.  'both' does both. (new in 0.7.2)


    datestubs( rangedict, inc=None,  ...  )

        Prepare a datetime-centric axis.  Returns a list of datetime stubs, 
        suitable for passing to axis() as its stublist arg.  See example set 4.
        Args:
            rangedict:      the dict returned by findrange_result() 
            inc (str):      the desired increment, one of ['day', 'week', 'month',
                            '3month', 'year', 'fy', 'hour', '3hour']
            crossings (bool): if True only make a stub when crossing an inc boundary
            dtformat (str): datetime format for the stubs, see also setdt()
            terse (bool):   if True use a terser version of the format
        Returns:
            list:  a list of (utime, stubtext) pairs, to use as stublist


    plotlabels(  ...  )

        Add axis labels or a plot title to your data-scaled plotting area.
        Typical example:  plotlabels(xlabel='Month', ylabel='Percent', ylabelpos=-100)
        Args: 
            title (str):     a plot title for above the plot area
            xlabel (str):    a descriptive label for below the X axis
            ylabel (str):    a descriptive label for left of the Y axis 
            titlepos (int):  title's distance above top of plot area in native 
                             units; defaults to 5
            xlabelpos (int): xlabel's offset from bottom of plot area in 
                             native units; defaults to -40
            ylabelpos (int): ylabel's offset from left of plot area in 
                             native units; defaults to -60


    plotbacking(  ...  )

        Add an outline, background color, or background image to the 
        data-scaled plot area.
        Typical example:  plotbacking(color='#ccc')
        Args: 
            outline (bool): if True draw an outline 
            color (str):    fill with this color; defaults to None
            rounded:        if True (or list[2]) round the corners; see rect()
            image (str):    url of a JPG, PNG, GIF image (aspect ratio not preserved)


    catranges( axis  )

        Find the (min, max) in native units of where each currently defined
        category lies.  Specialized use ('multipanel' pattern); see example set 6.
        Args:
            axis (str):  either 'X' or 'Y'
        Returns:
            dict: one element per category, keyed on category name, and having a 
                  numeric tuple of (min, max)



Section 7. Plotting in a data-scaled space

    In these functions the x and y coordinates are usually numeric but can be  
    str category values if categorical space has been defined.  Datetime values
    must be converted to numeric using intdt() beforehand.


    line( x1, y1, x2, y2  )

        Draw a line in data-scaled space, using current line settings.  
        See also lin()
        Args:
            x1, y1: starting point in data-scaled units
            x2, y2: ending point      ''


    label( x, y, text,  ...  )

        Render text at x,y in data-scaled space, using current text settings.
        Args:
            x, y:  position in data-scaled units
            text:  the text to display, see also txt()
            anchor, adjust: temp overrides for adjust, anchor; see settext()


    rectangle( cx, cy, width, height,  ...  )

        Render a rectangle with its center at x,y in data-scaled space.
        Args:
            x, y (float):   location of rectangle's center in data-scaled units
            height (float): height of rectangle                    ''
            width: (float): width of rectangle                     ''
            color (str):    color of fill; defaults to '#afa'; None == no fill
            outline (bool): if True outline the graphic 
            rounded:        if True (or list[2]) round the corners; see rect() 
            opacity (float): defaults to 1.0 (opaque); 0.0 == transparent.


    arrow( x1, y1,  ...  )

        Render an arrow in data-scaled space using current line settings.
        Line starting point is always x1,y1.  Location of arrowhead is defined 
        either by supplying x2,y2 or by supplying direction and magnitude.
        Args:
            x1, y1 (float):  Location of starting point in data-scaled units
            x2, y2 (float):  Specify location of arrowhead as a point 
            direction, magnitude:  Specify location of arrowhead as a vector using 
                             direction (in degrees where 0 is straight up) along with 
                             magnitude in native units.
            headlen (int):   Length of arrowhead in native units; defaults to 18
            headwid (float): theta controlling stoutness of arrowhead; default is 0.3
            tiptype (str):   one of ['solid', 'line', or 'barb']; defaults to 'solid'
            tipcolor (str):  color of tip; defaults to '#888'
            opacity (float): for tip; defaults to 1.0 (opaque)


    errorbar( x=None,  ...  )

        Render an error bar in data-scaled space using current line settings.
        The x arg is always required.  In addition, either y and erramt, or else 
        ymin and ymax, must be specified.  These descriptions are worded for 
        vertical bars; the sense here of X vs. Y (etc) should be juxtaposed 
        when horiz=True.
        Typical example 1:  errorbar(x=20, y=0.75, erramt=0.07)
        Typical example 2:  errorbar(x=20, ymin=0.73, ymax=0.85)
        Args:
            x:                  lateral location of bar in data-scaled units
            y, erramt (float):  specify bar as: origin and bar's length up/down  ''
            ymin, ymax (float): specify bar as: ranging from ymin to ymax        ''
            tailsize (int):     size of the tails in native units; defaults to 5
            horiz (bool):       if True do horizontal error bars; defaults to False
            shift (int):   adjust the lateral location (native units); defaults to 0


    bar( x=None, y=None,  ...  )

        Render a column bar in data-scaled space.  x and y args are always required.
        These descriptions are worded for vertical bars; the sense here of 
        X vs. Y (etc) should be juxtaposed when horiz=True.
        Args:
            x:             lateral location of bar in data-scaled units
            y (float):     height of bar               ''
            ybase (float): origin of column bar; defaults to bottom of plot area.
                           Typical use is with stacked bars, or eg. ybase=0 to get 
                           downward bars for negative values.
            width (int):   width of bar in native units.
            color (str):   fill color of bar; defaults to '#afa'
            opacity (float): defaults to 1.0 (opaque)
            outline (bool):  if True outline the bar using current line settings
            rounded:       if True (or list[2]) round the corners; see rect()
            horiz (bool):  if True do horizontal bars; defaults to False
            shift (int):   adjust the lateral location (native units); defaults to 0


    boxplot( info, x=None,  ...  )

        Render a vertical Tukey box & whisker plot in data plotting space, based on 
        5th, 25th, 50th, 75th, 95th percentiles as previously computed by numinfo().
        Args:
            info (dict): as returned from numinfo(percentiles=True)
            x:           X location of boxplot 
            width (int): width of boxplot in native units
            color (str): fill color of boxplot; defaults to '#ccc'
            n_at_y (float): render an 'N = ' label at this data-scaled Y location
            shift (int): adjust X location by this amount in native units


    datapoint( x=None, y=None,  ...  )

        Render a data point, either geometric or character-based.  Typical use is 
        scatterplots and similar.  See example sets 2 and 3 for depictions / details.
        See also setclustering() and its use in example sets 4 and 5.
        Args:
            x, y:         location of data point in data-scaled units* 
            symbol (str): rendered symbol type; defaults to '(vcircle)'; see example 3
            diameter:     diameter of symbol in native units
            color (str):  color of symbol; defaults to '#777'
            opacity (float): defaults to 0.7 (somewhat transparent)
            adjust:       numeric tuple to adjust location by (x, y) in native units
            backing (str): a second symbol type; allows composite symbols
            stretch:      a numeric tuple eg. (1.2, 1.0) to stretch the symbol
                          horizontally or vertically to get eg. an ellipse.  Can only
                          be used with vcircle* or vrect* symbol types.
            *except with:
             nativecoords (bool): if True the x, y location is taken to be native units,
                          for standalone uses such as legends 
         


    curvebegin(  ...  )

        Begin a new lineplot curve or filled band in data-scaled space.
        Subsequent points in the curve are then given using curvenext().
        See example set 2 for depiction / details.
        Args: 
            x, y:           location of first data point in data-scaled units
            y2:             if specified we'll be doing a band filled from y to y2    ''
            fill (str):     fill color; if y2 not given fill is from bottom of plot area
            fillopacity:    defaults to 0.7 for somewhat transparent
            stairs (bool):  if True do a stairstep-style plot (see example 5)
            onbadval (str): line rendering on unusable value, either 'bridge' or 'gap'
            shift (float):  amount to offset the curve left or right, in native units 


    curvenext( x=None, y=None,  ...  )

        Continue a lineplot curve or filled band in data-scaled space.
        Args:
            x, y:           location of next data point in data-scaled units
            y2:             next y2 location if doing filled band



Section 8: Legends

    To create a legend, first call legenditem() once for each color, symbol, or 
    line style you're displaying, to 'register' it.  Then call legendrender() 


    legenditem( sample=None, label=None,  ...  )

        Define a legend item, to be rendered later using legendrender().
        The item can be for a color sample, a data point symbol, or line style
        as determined by sample arg.  See example set 3 for depiction / details.
        For line style the current line settings are captured.
        Typical example:  legenditem(sample='circle', color='#a33', label='Group A')
        Args:  
            sample (str):  the type of legend item, either a color sample 
                           ('square' or 'circle'), or 'symbol' or 'line'.
            label (str):   legend item's label
            color (str):   color, used only with sample='square' or sample='circle' 
            ewidth (int):  set legend item's occupied width (format='across' only)

            The following are used only with sample='symbol':
              symbol (str):  symbol name as given with datapoint() 
              diameter (int): symbol diameter; defaults to 10
              backing (str): for composite symbols, a 2nd symbol name; see datapoint()
              opacity (float): defaults to 0.7 (somewhat transparent)
          


    legendrender(  ...  )

        Render a legend showing items defined earlier via legenditem().
        Typical example:  legendrender(format='across', adjust=(10, 20), sep=10 )
        See also example set 3.
        Args: 
            location (str): where to place the legend in your svg graphic.  One of
                            ['top', 'bottom', 'in_adjust'].  Defaults to 'top'.
                            Use 'top' to place legend in top-left corner; use 'bottom' 
                            for bottom-left corner.  For 'in_adjust' see below.
                            The adjust arg is often needed for best results.  
            adjust:         a numeric tuple (x, y) to fine-tune legend location, or with
                            'in_adjust' to explicitly set legend's upper-left location.
                            Native units.
            format (str):   how the items are listed, either 'down', 'across', or 
                            'parkinglot' which is similar to 'across' but with slanted
                            labels.  Defaults to 'down'.
            sep (int):      an additional amount of separation between legend items
                            in native units; defaults to 0.
            sampsize (int): diameter of color samples in native units; defaults to 8
            lnlen (int):    length of line samples in native units; defaults to 20
            title (str):    title for the legend, appears at top
            outline (bool): if True outline the legend using current line settings
            rounded:        if True (or list[2]) round the outline's corners; see rect()




Section 9: Conversion functions, data-scaled space to native



    nu( axis, dataval  )

        For a value in data-scaled space return its native coordinate.
        Args:
            axis (str):  either 'X' or 'Y'
            dataval   :  a value in data-scaled space.  If this axis is set up
                         with numeric scaling, this is a number.  Datetime values 
                         must be converted to numeric first using intdt().
                           If this axis is using categorical scaling, then this 
                         should be a category name.
                           This can also be special strings 'min' or 'max' which 
                         evaluate to the plot area minima or maxima.
        Returns:
            int:         native coordinate 


    nx( dataval  )

        Convenience equivalent for  nu('X', dataval) 


    ny( dataval  )

        Convenience equivalent for  nu('Y', dataval) 


    nmin( axis  )

        Convenience equivalent for  nu(axis, 'min') 


    nmax( axis  )

        Convenience equivalent for  nu(axis, 'max') 


    natpair( x, y  )

        Convert a data-scaled coordinate pair to native coordinate pair.
        Args:
            x, y:   a coordinate pair in data-scaled units
        Returns:
            int: natx, int: naty  ... coordinate pair in native units


    natdist( axis, datadist  )

        Convert a data-scaled distance to a distance in native units.
        Args:
            axis (str):       'X' or 'Y'
            datadist (float):  a distance in data-scaled units
        Returns:
            int:   a distance in native units


    inrange( axis, dataval  ) # was named inspace()

        See if dataval is within the axis space.
        Args:
            axis (str):  'X' or 'Y'
            dataval:     a value in data-scaled units, see nu()
        Returns:
            True if dataval in axis range, False otherwise.


    dmin( axis  )

        Get the minima of current data-scaled space.
        Args:
            axis (str):   'X' or 'Y'
        Returns:
            float:   minima of data-scaled space


    dmax( axis  )

        Get the maxima of current data-scaled space.
        Args:
            axis (str):   'X' or 'Y'
        Returns:
            float:   maxima of data-scaled space



Section 10: Datetime conversion / utility functions

    See setdt() in Section 2 to set your current datetime format. 


    intdt( dtstr  )

        Return integer equivalent of a datetime string.  When working with
        datetime data, conversion to integer is needed in order to use 
        most datadraw functions.
        Args:
            dtstr (str):  datetime string in your current datetime format
        Returns:
            int:   integer equivalent, for supplying to


    outdt( utime  )

        Format a datetime string from an integer utime value 
        Args:
            utime (int):  a utime value; this is what intdt() returns
        Returns:
            str:   a datetime string using your current date format


    dtdiff( dt1, dt2, outunits='days'  )

        Find the difference between two datetime strings.
        Args:
            dt1, dt2 (str): two datetime strings in your current date format
            outunits (str): desired result, one of ['days', 'hours', 
                            'minutes', 'seconds']
        Returns:
            int: difference of dt1 minus dt2 expressed in requested units



Section 11. Misc functions



    write_svgfile(svgcode, filename  )

    Utility to write svg to a file with proper file-centric headers.
    If the filename ends in .svg you can display it in a web page using an 'img' tag,
    control height and width conveniently, and browser caching may come into play.
    However there are some caveats: tooltips won't work; HTML special character 
    constructs won't work; and your SVG can't be influenced by your host web 
    page's CSS.  See also:
        https://stackoverflow.com/questions/24835497
        https://www.w3.org/TR/SVG/styling.html#StyleElementExample
    Args:
        svgcode (str):  SVG code buffer
        filename (str, pathname):  filename



End of DataDraw function reference.
Documentation (c) 2024 Steve Grubb