Skip to content

Formatting

Jeffrey Heer edited this page Jan 22, 2016 · 8 revisions

WikiAPI ReferenceFormatting

String Formatting

Templates

# dl.template(text)

Generates and returns a string template function for data objects. The input argument text provides a string template. Within the template, variables may be included as {{foo}}, which is later replaced with the foo property of an input data object.

In addition, template variables support a number of filters for text transformation. Filters are specified within a template variable using a pipe-delimited syntax ({{property | filter1 | filter2 }}). Some filters may take one or more arguments ({{property | filter:arg1,arg2 }}). The available filters are:

  • length - return the length of a string.
  • lower - maps a string to lowercase (calls String.toLowerCase()).
  • upper - maps a string to uppercase (calls String.toUpperCase()).
  • lower-locale - maps a string to lowercase (calls String.toLocaleLowerCase()).
  • upper-locale - maps a string to uppercase (calls String.toLocaleUpperCase()).
  • trim - remove whitespace at the beginning and end of a string (calls String.trim()).
  • left:n - returns the n left-most characters of a string.
  • right:n - returns the n right-most characters of a string.
  • mid:n - returns the n central characters of a string.
  • slice:a,b - returns a substring according to String.slice(a, b).
  • pad:n,pos - pads the string with whitespace using dl.pad using the provided length (n) and optional position argument (pos).
  • truncate:n,pos - truncates the string using dl.truncate with the provided length (n) and an optional position argument (pos).
  • number:fmt - formats the string as a number using the provided format (fmt) string. The filter uses d3-format's formatting utilities and accepts a valid D3 number format pattern. Note that the format string must be quoted (e.g., ',.2f').
  • time:fmt - formats the string as a local datetime using the provided format (fmt) string. The filter uses d3-time-format's time formatting utilities and accepts a valid D3 time format pattern. Note that the format string must be quoted (e.g., '%A').
  • time-utc:fmt - formats the string as a UTC datetime using the provided format (fmt) string. The filter uses d3-time-format's time formatting utilities and accepts a valid D3 time format pattern. Note that the format string must be quoted (e.g., '%A').
  • month - formats an integer month value as a month name (O -> 'January', ..., 11 -> 'December').
  • month-abbrev - formats an integer month value as an abbreviated month name (O -> 'Jan', ..., 11 -> 'Dec').
  • day - formats an integer day of week value as day name (O -> 'Sunday', ..., 6 -> 'Saturday').
  • day-abbrev - formats an integer day of week value as an abbreviated day name (O -> 'Sun', ..., 6 -> 'Sat').
var t = dl.template("Hi {{name}}, the day is {{stamp|time:'%A'}}.");
t({name: "Avery", stamp: new Date(2015, 4, 1)}); // Hi Avery, the day is Friday.

Format Values

Datalib provides a variety of methods for formatting numerical and datetime values. Under the hood, datalib uses the excellent d3-format and d3-time-format modules.

# dl.format.number(specifier)

Format numerical values. Returns a new format function for the given string specifier. The returned function takes a number as the only argument, and returns a string representing the formatted number. The general form of a specifier is: [​[fill]align][sign][symbol][0][width][,][.precision][type]. For more details, see the documentation for d3-format's locale.format method.

# dl.format.numberPrefix(specifier, value)

Format numerical values according to an SI prefix. Similar to dl.format.number, except the returned function will convert values to the units of the appropriate SI prefix for the specified numeric reference value before formatting in fixed point notation. For more details, see the documentation for d3-format's locale.formatPrefix method.

# dl.format.time(format)

Format datetime values in the local timezone. Returns a new datetime format function for the given string specifier. For more details, see the documentation for d3-time-format's locale.format method.

# dl.format.utc(utc)

Format datetime values in Coordinated Universal Time (UTC). Returns a new datetime format function for the given string specifier. For more details, see the documentation for d3-time-format's locale.utcFormat method.

Auto-Format Values

# dl.format.auto.number([specifier])

Automatically format numerical values. Returns a formatting function that automatically determines the precision of the printed numbers by removing trailing zeros. An optional d3-format specifier string can be used to refine the formatting type and style. By default, decimal formatting with thousands grouping (format string ',') is used.

var f1 = dl.format.auto.number();
f1(100) // -> '100'
f1(0.1*3) // -> '0.3'
f1(1.234560e3) // -> '1,234.56'

var f2 = dl.format.auto.number('s'); // use SI units
f2(100) // -> '100'
f2(0.1*3) // -> '300m'
f2(1.23e3) // -> '1.23k'

# dl.format.auto.linear(domain, [tickCount, specifier])

Automatically format a linear range of numbers using shared units. Returns a formatting function useful for printing numbers in a consistent format along a linear chart axis. The domain argument is an array that should contain the minimum and maximum values of the linear range at the first and last array indices. The optional tickCount argument indicates the desired number of labels (tick marks) along the range (default 10). Finally, the optional specifier argument can be used to refine the formatting type and style.

# dl.format.auto.time()

Automatically format local datetime values in manner useful for labeling timelines or chart axes. Returns a formatting function that automatically adjusts the format based on the time units. Datetime values falling on a specific time unit boundary (year, month, day, etc) will print the value of the corresponding time unit.

var f = dl.format.auto.time();
f(new Date(2000, 0, 1) -> '2000'
f(new Date(2000, 1, 1) -> 'February'
f(new Date(2000, 1, 2) -> 'Wed 02'

# dl.format.auto.utc()

Automatically format UTC datetime values. This method is identical to dl.format.auto.time, except that it uses UTC time values.

Format Tables

# dl.format.table(data[, options])

Create a formatted print string for table data, suitable for console printing.

The options hash may contain the following entries:

  • separator: The string to use to separate adjacent fields in a record. The default is a single space ' '.
  • minwidth: The minimum width (in characters) allocated to field names. The default is 8 characters. If the values in a field never result in a string longer than minwidth characters, the field name will be truncated. If both the value strings and field name are less than minwidth then the resulting printed column may be narrower than minwidth characters.
  • maxwidth: The maximum width (in characters) allocated to a printed column. The default is 15 characters. If either the value strings or field name exceed this length, they will be truncated.
  • start: The row index at which to start printing the table. The default is 0.
  • limit: The number of rows to print, or -1 for all rows. The default is -1.
var data = dl.csv('data/stocks.csv'); // import csv file

// print the full table to the console
console.log(dl.format.table(data)); 

// print the full table, with a maximum of 10 characters per column
console.log(dl.format.table(data, {maxwidth:10})); 

// print 100 rows, starting at row 50
console.log(dl.format.table(data, {start:50, limit:100})); 

# dl.format.summary(summary)

Create a formatted print string for a set of summary profiles generated using dl.summary, suitable for console printing. If the summary argument was not generated by dl.summary, this method will treat the input as a data table and invoke dl.summary internally prior to creating the print string.

var data = dl.csv('data/stocks.csv'); // import csv file

// generate summary profiles, then print to console
var sum = dl.summary(data);
console.log(dl.format.summary(sum));

// prints the same result as above, but invokes dl.summary internally
console.log(dl.format.summary(data));

Locales

Datalib supports changing the formatting options to match conventions in various parts of the world. The default locale for both number and datetime formatting is American English ('en-US'). The locale methods allow one to change this to other languages and regions.

# dl.format.locale(locale)

Set the locale for number and datetime formatting. The locale format input is a (case-insensitive) locale string of the form "en-US", "de-DE", "zh-CN", etc. For a list of supported locales, see either the d3-format or d3-time-format locale documentation.

dl.format.locale('de-DE'); // set to German locale formatting
dl.format.number('$,.2f')(1200.37); // -> '1.200,37 €'
dl.format.time('%b %Y')(new Date(2000,9)); // -> 'Okt 2000'

# dl.format.numberLocale(locale)

Set the locale for number formatting. The locale format input can either be a (case-insensitive) locale string of the form "en-US", "de-DE", "zh-CN", etc, or a d3-format locale object. For a list of supported locales, see the d3-format documentation.

# dl.format.timeLocale(locale)

Set the locale for datetime formatting. The locale format input can either be a (case-insensitive) locale string of the form "en-US", "de-DE", "zh-CN", etc, or a d3-time-format locale object. For a list of supported locales, see the d3-time-format documentation.

You can’t perform that action at this time.