Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

### Added

- The smooth, density and violin layers now accept date, datetime and time
value axes (#250). The computation runs on epoch-microsecond numbers and
the result is converted back to timestamps, so a date axis stays a
temporal axis (rendered as datetimes, with labels falling back to plain
dates at midnight). Datetime labels at exact midnight now render as plain
dates everywhere.
- Bar and histogram layers now support the `linewidth` and `linetype`
aesthetics.
- New `TABULATE` clause renders a query result as a table instead of a
Expand Down Expand Up @@ -136,6 +142,9 @@ determines whether text boxes get drawn and additional settings `padding`,

### Fixed

- Density and violin layers now return their rows ordered along the value
axis. Grouped densities previously came back unordered, which renderers
that draw in row order turned into zigzagging fills.
- A timestamp with a time zone is now written as a timestamp in UTC
(`2024-01-02T03:04:05Z`) wherever ggsql shows a value as text, rather than
as the name of its Arrow type (#595).
Expand Down
4 changes: 1 addition & 3 deletions doc/syntax/layer/type/smooth.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,9 @@ $$

The default `method => 'nw'` might be too coarse for timeseries.

<!-- Ideally, we would just use the date here directly but we currently require numeric data -->

```{ggsql}
SELECT * FROM ggsql:airquality
VISUALISE Epoch AS x, Temp AS y
VISUALISE Date AS x, Temp AS y
DRAW point
DRAW smooth
```
Expand Down
82 changes: 81 additions & 1 deletion src/execute/scale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -772,11 +772,25 @@ pub fn coerce_column_to_type(
Ok(None)
} else {
let s = str_arr.value(i);
ArrayElement::from_date_string(s)
// Accept datetime strings too, truncating to
// the date: some drivers hand temporal columns
// back as strings, and a stat may have
// produced datetimes on a date axis.
let parsed = ArrayElement::from_date_string(s)
.and_then(|e| match e {
ArrayElement::Date(d) => Some(d),
_ => None,
})
.or_else(|| {
ArrayElement::from_datetime_string(s).and_then(|e| match e
{
ArrayElement::DateTime(dt) => {
Some((dt.div_euclid(86_400_000_000)) as i32)
}
_ => None,
})
});
parsed
.ok_or_else(|| {
GgsqlError::ValidationError(format!(
"Column '{}' row {}: Cannot coerce string '{}' to date (expected YYYY-MM-DD)",
Expand All @@ -799,6 +813,19 @@ pub fn coerce_column_to_type(
},

ArrayElementType::DateTime => match dtype {
// Date → Datetime upcast (a date is midnight on that day). Stats
// like smooth return timestamps even for date axes, so the other
// layers' date columns arrive here unconverted.
DataType::Date32 => {
cast_array(column, &DataType::Timestamp(TimeUnit::Microsecond, None)).map_err(
|e| {
GgsqlError::ValidationError(format!(
"Cannot coerce column '{}' from date to datetime: {}",
column_name, e
))
},
)?
}
DataType::Utf8 => {
let str_arr = as_str(column)?;
let dt_vec: Vec<Option<i64>> = (0..str_arr.len())
Expand Down Expand Up @@ -1004,6 +1031,59 @@ pub fn resolve_scales(spec: &mut Plot, data_map: &mut HashMap<String, DataFrame>
panel_templates.insert(aesthetic.clone(), spec.scales[idx].clone());
}

// Reconcile a temporal transform with the materialized data. The
// transform was inferred from the source schema, but a stat may have
// changed a column's temporal flavour since (e.g. smooth computes
// over epoch numbers and returns timestamps even for a date axis).
// Re-infer from the actual data so coercion and labelling use the
// right flavour; user-explicit transforms (VIA ...) are kept.
if !spec.scales[idx].explicit_transform {
let temporal_transform = spec.scales[idx]
.transform
.as_ref()
.map(|t| t.transform_kind())
.is_some_and(|k| {
matches!(
k,
TransformKind::Date | TransformKind::DateTime | TransformKind::Time
)
});
if temporal_transform {
let column_dtypes: Vec<arrow::datatypes::DataType> =
find_columns_for_aesthetic(&spec.layers, &aesthetic, data_map, &aesthetic_ctx)
.iter()
.map(|c| c.data_type().clone())
.filter(|dt| {
matches!(
dt,
arrow::datatypes::DataType::Date32
| arrow::datatypes::DataType::Date64
| arrow::datatypes::DataType::Timestamp(_, _)
| arrow::datatypes::DataType::Time32(_)
| arrow::datatypes::DataType::Time64(_)
)
})
.collect();
if !column_dtypes.is_empty() {
if let Ok(common_dtype) = crate::plot::scale::coerce_dtypes(&column_dtypes) {
// A temporal transform is mutually exclusive with a
// map projection: projections stamp their position
// scales with TransformKind::Geographic, so a scale
// that reaches this branch is never a map scale.
let kind = infer_transform(&spec.scales[idx], &common_dtype, false);
if Some(kind)
!= spec.scales[idx]
.transform
.as_ref()
.map(|t| t.transform_kind())
{
spec.scales[idx].transform = Some(Transform::from_kind(kind));
}
}
}
}
}

// Infer target type and coerce columns if needed
// This enables e.g. SCALE DISCRETE color FROM [true, false] to coerce string "true"/"false" to boolean
if let Some(target_type) = infer_scale_target_type(&spec.scales[idx]) {
Expand Down
Loading
Loading