Working with Dates

This is a tutorial on how to prepare temporal data for use with Lux. To display temporal fields in Lux, the column must be converted into Pandas's datetime objects. Lux automatically detects attribute named as date, month, year, day, and time as a datetime field and recognizes them as temporal data types. If you're temporal attributes do not have these names, read more to find out how to work with temporal data types in Lux.

In [ ]:
import pandas as pd
import lux
from lux.vis.Vis import Vis
In [ ]:
# Collecting basic usage statistics for Lux (For more information, see: https://tinyurl.com/logging-consent)
lux.logger = True # Remove this line if you do not want your interactions recorded

Converting Strings to Datetime objects

To convert column referencing dates/times into datetime objects, we use pd.to_datetime, as follows:

pd.to_datetime(['2020-01-01', '2020-01-15', '2020-02-01'],format="%Y-%m-%d")

As a toy example, a dataframe might contain a record_date attribute as strings of dates:

In [ ]:
df = pd.DataFrame({'record_date': ['2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01','2020-06-01',],
                   'value': [10.5,15.2,20.3,25.2, 14.2]})

df

By default, the record_date attribute is detected as an object type as Pandas's data type dtype:

In [ ]:
df.dtypes

Since record_date is detected as an object type in Pandas, the record_date field is recognized as a nominal field in Lux, instead of a temporal field:

In [ ]:
df.data_type

The typing has implications on the generated visualizations, since nominal chart types are displayed as bar charts, whereas temporal fields are plotted as time series line charts.

In [ ]:
vis = Vis(["record_date","value"],df)
vis

To fix this, we can convert the record_date column into a datetime object by doing:

In [ ]:
df["record_date"] = pd.to_datetime(df["record_date"],format="%Y-%m-%d")
df["record_date"]

After changing the Pandas data type to datetime, we see that date field is recognized as temporal fields in Lux.

In [ ]:
df.data_type
In [ ]:
vis.refresh_source(df)
vis

Lux automatically detects the temporal attribute and plots the visualizations across different timescales to showcase any cyclical patterns. Here, we see that the Temporal tab displays the yearly, monthly, and weekly trends for the number of stock records.

In [ ]:
from vega_datasets import data
df = data.stocks()
In [ ]:
df.recommendation["Temporal"]

Advanced Date Manipulation

You might notice earlier that all the dates in our example dataset are the first of the month. In this case, there may be situations where we only want to list the year and month, instead of the full date. Here, we look at how to handle these cases.

Below we look at an example stocks dataset that also has month_date field with each row representing data for the first of each month.

In [ ]:
df.dtypes
In [ ]:
vis = Vis(["monthdate","price"],df)
vis

If we only want Lux to output the month and the year, we can convert the column to a PeriodIndex using to_period. The freq argument specifies the granularity of the output. In this case, we are using 'M' for monthly. You can find more about how to specify time periods here.

In [ ]:
df["monthdate"] = pd.DatetimeIndex(df["monthdate"]).to_period(freq='M')
In [ ]:
vis.refresh_source(df)
vis

Specifying Intents With Datetime Fields

The string representation seen in the Dataframe can be used to filter out specific dates.

For example, in the above stocks dataset, we converted the date column to a PeriodIndex. Now the string representation only shows the granularity we want to see. We can use that string representation to filter the dataframe in Pandas:

In [ ]:
df[df["monthdate"] == '2008-11']

We can also use the same string representation for specifying an intent in Lux.

In [ ]:
vis = Vis(["monthdate=2008-11","price","symbol"],df)
vis