-
I'd like to show a weighted average of some data I'm already showing on a geo plot. I wrote a transform function that should calculate the value.
I can also show some text on the plot where I want the weighted average to go e.g.
I'm at a loss for where to put the weighted average function in the Text mark, or if I need to precalculate it and do a lookup in the text mark for each facet somehow. Thanks for any help you can provide. Paul |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Sounds like you want the groupZ transform; you probably don’t need a custom transform for this. Assuming a data structure like this of weighted values: data = [
{value: 1, weight: 1, facet: "a"},
{value: 2, weight: 3, facet: "a"},
{value: 3, weight: 4, facet: "a"},
{value: 4, weight: 8, facet: "a"},
{value: 3, weight: 1, facet: "b"},
{value: 5, weight: 9, facet: "b"},
{value: 3, weight: 1, facet: "c"},
{value: 2, weight: 2, facet: "c"},
{value: 1, weight: 1, facet: "c"}
] You can plot the (non-weighted) mean of observed values using the groupZ transform with the mean reducer like so: Plot.plot({
marks: [
Plot.dot(data, {y: "weight", fx: "facet"}),
Plot.tickY(data, Plot.groupZ({y: "mean"}, {y: "weight", fx: "facet", stroke: "red"}))
]
}) To compute the weighted mean instead, you can write a custom reducer instead of mean. If you don’t supply an input channel to your custom reducer (i.e., you only define it on the outputs of the groupZ transform, and not on the inputs), then your custom reducer will be passed the data instead. Using D3 that could be written as: function weightedMean(data) {
return d3.sum(data, (d) => d.value * d.weight) / d3.sum(data, (d) => d.weight);
} To use: Plot.plot({
marks: [
Plot.dot(data, {y: "weight", fx: "facet"}),
Plot.tickY(data, Plot.groupZ({y: weightedMean}, {fx: "facet", stroke: "blue"})),
Plot.text(data, Plot.groupZ({y: weightedMean, text: weightedMean}, {fx: "facet", fill: "blue", stroke: "white"}))
]
}) |
Beta Was this translation helpful? Give feedback.
Sounds like you want the groupZ transform; you probably don’t need a custom transform for this.
Assuming a data structure like this of weighted values:
You can plot the (non-weighted) mean of observed values using the groupZ transform with the mean reducer like so: