|
| 1 | +--- |
| 2 | +title: "Multi-Layer Plot" |
| 3 | +description: "Combining multiple geometric layers in one visualization" |
| 4 | +image: thumbnails/multi-layer.svg |
| 5 | +categories: [layers, advanced] |
| 6 | +order: 5 |
| 7 | +--- |
| 8 | + |
| 9 | +Multi-layer plots combine different geometric elements (geoms) to create richer visualizations. Each `DRAW` clause adds a new layer. |
| 10 | + |
| 11 | +## Code |
| 12 | + |
| 13 | +```{ggsql} |
| 14 | +SELECT Date, Temp FROM ggsql:airquality |
| 15 | +VISUALISE Date AS x, Temp AS y |
| 16 | +DRAW line |
| 17 | + SETTING color => 'steelblue' |
| 18 | +DRAW point |
| 19 | + SETTING size => 4, color => 'darkblue' |
| 20 | +SCALE x VIA date |
| 21 | +LABEL |
| 22 | + title => 'Temperature with Line and Points', |
| 23 | + x => 'Date', |
| 24 | + y => 'Temperature (F)' |
| 25 | +``` |
| 26 | + |
| 27 | +## Explanation |
| 28 | + |
| 29 | +- The first `DRAW line` creates a line connecting all points |
| 30 | +- The second `DRAW point` adds point markers at each data point |
| 31 | +- `SETTING` on each layer controls that layer's visual properties |
| 32 | +- Both layers share the same x and y mappings from `VISUALISE` |
| 33 | + |
| 34 | +## Variations |
| 35 | + |
| 36 | +### Different Aesthetics Per Layer |
| 37 | + |
| 38 | +Each layer can have its own aesthetic mappings using `MAPPING`: |
| 39 | + |
| 40 | +```{ggsql} |
| 41 | +SELECT Date, Temp, Ozone FROM ggsql:airquality |
| 42 | +VISUALISE Date AS x |
| 43 | +DRAW line |
| 44 | + MAPPING Temp AS y, 'Temperature' AS color |
| 45 | +DRAW line |
| 46 | + MAPPING Ozone AS y, 'Ozone' AS color |
| 47 | +SCALE x VIA date |
| 48 | +LABEL |
| 49 | + title => 'Temperature and Ozone Over Time', |
| 50 | + x => 'Date', |
| 51 | + y => 'Value' |
| 52 | +``` |
| 53 | + |
| 54 | +### Layers from Different Data Sources |
| 55 | + |
| 56 | +Use `MAPPING ... FROM` to pull each layer from different CTEs: |
| 57 | + |
| 58 | +```{ggsql} |
| 59 | +WITH temps AS ( |
| 60 | + SELECT Date, Temp as value FROM ggsql:airquality |
| 61 | +), |
| 62 | +ozone AS ( |
| 63 | + SELECT Date, Ozone as value FROM ggsql:airquality WHERE Ozone IS NOT NULL |
| 64 | +) |
| 65 | +VISUALISE |
| 66 | +DRAW line |
| 67 | + MAPPING Date AS x, value AS y, 'Temperature' AS color FROM temps |
| 68 | +DRAW point |
| 69 | + MAPPING Date AS x, value AS y, 'Ozone' AS color FROM ozone |
| 70 | + SETTING size => 3 |
| 71 | +SCALE x VIA date |
| 72 | +LABEL |
| 73 | + title => 'Temperature vs Ozone', |
| 74 | + x => 'Date', |
| 75 | + y => 'Value' |
| 76 | +``` |
0 commit comments