Variable color a line based on a scale (using Vega-Lite)

I have here a line that represents a temperature (over time) that I would like to color with cloud coverage data from the same point in time. I kind of faked it in here by putting circle marks over the line: https://observablehq.com/@kpm-at-hfi/first-use-of-vega-lite-looking-at-temperatures-and-sky-condi

I thought I remember seeing some population data examples that made me think I could do this.

Any pointers?

Here’s a first attempt. The approach I took was to render each type of weather (the “clouds” field) as a separate line, with the line’s y-value (tmpf) undefined when the weather is not the corresponding type.

The data is generated using d3.cross:

clouds_data = d3.cross(weather_data, clouds).map(([{tmpf, date, clouds}, c]) => ({date, clouds: c, tmpf: clouds === c ? tmpf : null}))

The downside of this approach (other than being a little slow) is that when the “clouds” value changes, you get a gap. This makes sense—a line’s value is only defined at each data point, so there are multiple logical strategies for how to color the line when the color changes between data points. For example, you might want to switch colors halfway between the two data points, or even use a smooth gradient.

1 Like

Here’s how I would do this in D3:

Wow, one learns a lot when @mbostock refactors your code. Thanks very much for taking a look at this! Going with D3 makes sense… I was probably a bit too ambitious to try this as my first got with Vega-Lite.

1 Like