Skip to content

td-plot

Draw charts in the database with TD_PLOT: the package's plot_* functions first, raw SQL for what they don't cover.

Source file

Lives at tdfs4ds/skills/td-plot/SKILL.md.


name: "Teradata TD_PLOT: charts drawn in the database" description: "Generate code to draw charts in Teradata Vantage with TD_PLOT, so no row leaves the database: tdfs4ds.plot_in_database for any table or view, plot_feature / plot_features for stored feature values, plot_dataset, plot_correlation, plot_historian for historian tables, and raw EXECUTE FUNCTION TD_PLOT SQL for what they don't cover. Invoke when the user wants a line, scatter, bar, histogram, correlation matrix or small multiples from Vantage in Python. SKIP when a business user asks for a chart in the chat (use ca-plot), and for a lineage diagram (use fs-lineage)." argument-hint: "[table, dataset or feature][x] [y][series]" allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"


Generate code that draws a chart with Teradata's TD_PLOT. The image is rendered in the database and only the image comes back: no row leaves Vantage.

User context: $ARGUMENTS

Step Skill Why
Before fs-setup Open the session and select the feature store.
Sibling ca-plot The same charts, asked in natural language in the chat.
Pairs with td-kmeans Plot clusters after fitting.
Pairs with td-uaf-forecast Plot actual against forecast.
Pairs with td-uaf-feature Plot the distribution of a diagnostic.

Ask for any missing values before generating code: - What to plot: a table or view, a registered feature, a dataset, or a historian table. - Axes: x, y, and the column separating the series. - Chart: line, scatter, bar, histogram, correlation matrix.

The package's functions (use these first)

import tdfs4ds and an open session are enough.

Function Draws
tdfs4ds.plot_in_database(source, x, y, series=, kind=) Any table, view or SELECT.
tdfs4ds.plot_feature(feature, kind='distribution' or 'history') A feature's stored values.
tdfs4ds.plot_features([...]) Several features, one panel each.
tdfs4ds.plot_dataset(dataset, y=, x=, series=, kind=) Columns of a dataset view; defaults come from the catalog.
tdfs4ds.plot_correlation(dataset, columns) Correlation matrix, computed in one pass.
tdfs4ds.plot_historian(table, tags, id_values=) Tags of a historian (deep) table, one panel per tag.
tdfs4ds.plot_panels([tdfs4ds.plotting.panel(...), ...], layout=(2, 1)) Several panels in one TD_PLOT call.
import tdfs4ds
tdfs4ds.connect(database='<DATABASE>')

# Any table or view. For a line or a scatter, x_is_time says what kind of axis x is.
result = tdfs4ds.plot_in_database('<DATABASE>.<TABLE_OR_VIEW>', x='<X_COLUMN>', y='<VALUE_COLUMN>',
                                  series='<SERIES_COLUMN>', kind='line', x_is_time=True,
                                  title='<TITLE>')
tdfs4ds.show_plot(result)                       # shows it in a notebook
tdfs4ds.save_plot(result, '<CHART>.png')        # .png, .svg or .html

# A stored feature
tdfs4ds.show_plot(tdfs4ds.plot_feature('<FEATURE>'))                           # distribution, current values
tdfs4ds.show_plot(tdfs4ds.plot_feature('<FEATURE>', kind='history',            # values over time
                                       entity_values=['<ENTITY_VALUE>']))

# A dataset
tdfs4ds.show_plot(tdfs4ds.plot_dataset('<DATASET>', y=['<FEATURE_1>', '<FEATURE_2>']))
tdfs4ds.show_plot(tdfs4ds.plot_correlation('<DATASET>'))

Read result['error'] before anything else: a database error is returned whole, never raised. An invalid request raises ValueError. Also in the result: ok, image, n_points, n_series, series_capped, td_plot_sql (the SQL it ran), notes.

  • Several series: the 12 with the largest latest value are drawn. max_series= and series_order= ('largest', 'smallest', 'alphabetical', 'most_points') change that; result['series_capped'] says when some were left out.
  • Zoom: xlim=(low, high) filters the rows in SQL; ylim= sets the y axis.
  • Temporal source: pass qualifier='CURRENT VALIDTIME', never inside the query.
  • Index several curves on one chart: rebase=True on plot_historian.
  • Settings: tdfs4ds.PLOT_MAX_POINTS, PLOT_MAX_SERIES, PLOT_MAX_PANELS, PLOT_INTERACTIVE_MAX_POINTS (below it an interactive version is added).

Raw TD_PLOT (for what the functions don't cover)

teradataml has no class for TD_PLOT, and DataFrame.plot() is a different feature that brings data to the client. Run it as SQL:

import teradataml as tdml
from IPython.display import Image

cursor = tdml.execute_sql("""
EXECUTE FUNCTION TD_PLOT(
    SERIES_SPEC(
        TABLE_NAME(<DATABASE>.<TABLE_OR_VIEW>),
        ROW_AXIS(TIMECODE(<DATE_COLUMN>)),
        SERIES_ID(<SERIES_COLUMN>),
        PAYLOAD(FIELDS(<VALUE_COLUMN>), CONTENT(REAL))
    ),
    FUNC_PARAMS(
        PLOTS[(TYPE('line'), TITLE('<TITLE>'), XFORMAT('YYYY-MM-DD'))],
        WIDTH(900), HEIGHT(450)
    )
)""")
columns = [d[0].upper() for d in cursor.description]
image = cursor.fetchall()[0][columns.index('IMAGE')]    # read the IMAGE column by name
Image(image)

ROW_AXIS is TIMECODE(col) for a date or timestamp, SEQUENCE(col) for a number. The result is <SERIES_ID>, ROW_I, IMAGE. result['td_plot_sql'] from the functions above is a working example of any chart.

Several panels: pass several SERIES_SPEC(...) blocks, with FUNC_PARAMS(LAYOUT(cols, rows), PLOTS[(CELL(1, 1), SPAN(1, 1), TYPE('line'), ID(1)), (CELL(2, 1), SPAN(1, 1), TYPE('line'), ID(2))]). ID is the position of the SERIES_SPEC, and cells start at 1.

Param Values
TITLE, XLABEL, YLABEL (in PLOTS) Text, at most 127 characters.
TYPE (in PLOTS) 'line', 'scatter', 'bar', 'corr', 'mesh', 'wiggle', 'geometry'.
XFORMAT (in PLOTS; outside it is Error 3706) 'YYYY-MM-DD', 'YYYY-MM', 'DD/MM/YYYY', 'HH:MI'. Never date and time together; %Y is Error 9153.
YRANGE (in PLOTS) y range.
LEGEND (in PLOTS) A location inside the plot, such as 'best' or 'upper right'. 'outside' is Error 9153.
IMAGE 'png' (default), 'svg', 'jpg'.
WIDTH, HEIGHT Pixels.
COLORMAP(...) For mesh and geometry.

Limits measured on Vantage 20

  • WIDTH and HEIGHT are at least 400 (Error 3706 "Invalid WIDTH value").
  • No XRANGE on a time axis (Error 3706): filter the rows. xlim= does this.
  • Date format: XFORMAT('YYYY-MM-DD'), never %Y (Error 9153).
  • At most 1024 series per call (Error 9153). For a scatter of many entities, don't use the entity key as SERIES_ID, which gives one series per row. Use a constant column, or series=None with the functions above.
  • Temporal tables: a statement-level qualifier cannot sit over a derived table (Error 9330), and a temporal qualifier belongs at the start of the statement. The functions handle this by staging the rows in a volatile table.
  • Category bars: one series with the names as labels. A series per category draws broken bars.
  • Periods: a value over a period must be drawn as a step. plot_feature(kind='history') and plot_dataset do this; hand-written points give a sawtooth.

Rules

  • A chart is not a feature: upload_features cannot register an image. To keep the evidence, write what the chart shows in the business dictionary with tdfs4ds.genai.documentation.upload_business_dictionary_sections(df), where df has DATABASE_NAME, OBJECT_NAME, SECTION_NAME, SECTION_CONTENT.
  • Raw SQL has no parameter binding, so never put untrusted input into a table or column name.
  • The third-party package tdnpathviz (pip install tdnpathviz, not a dependency of tdfs4ds) also wraps TD_PLOT, with pair_plot and plot_elbow. Use it only for those.