Skip to content

Instantly share code, notes, and snippets.

@MstrVLT
Created October 9, 2024 21:41
Show Gist options
  • Save MstrVLT/151275609a6db8f1e0c7bb5adb14c2ca to your computer and use it in GitHub Desktop.
Save MstrVLT/151275609a6db8f1e0c7bb5adb14c2ca to your computer and use it in GitHub Desktop.
d3.js vue composable
export function useD3Scales(el, sample, width, height) {
const yScale = computed(() => {
return d3.scaleLinear()
.range([toValue(height) - 2 * 60, 0])
.domain([0, 100]);
})
const xScale = computed(() => {
return d3.scaleBand()
.range([0, toValue(width) - 2 * 60])
.domain(toValue(sample).map((s) => s.language))
.padding(0.4)
})
return { xScale, yScale }
}
export function useD3Bars(el, sample, yScale, xScale, width, height) {
onMounted(() => {
watchEffect(() => {
const h = toValue(height) - 2 * 60
const x = toValue(xScale)
const y = toValue(yScale)
const upd = (selection) => selection
.attr('x', (s) => x(s.language))
.attr('y', (s) => y(s.value))
.attr('height', (s) => Math.max(h - y(s.value), 0))
.attr('width', x.bandwidth())
d3.select(toValue(el))
.selectAll('.bar')
.data(toValue(sample), (d) => d?.language)
.join(
enter => enter
.append('rect')
.attr('class', 'bar')
.attr('fill', 'black')
.call(upd),
update => update
.call(upd),
)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment