Доработан график D3HorizontalChart

This commit is contained in:
ts_salikhov 2022-10-04 13:55:18 +04:00
parent a965a9b693
commit 74b309ee87

View File

@ -33,8 +33,8 @@ const D3HorizontalChart = memo((
useEffect(() => {
if (width < 100 || height < 100) return
const _width = width - margin.left - margin.right
const _height = height - margin.top - margin.bottom
const chartWidth = width - margin.left - margin.right
const chartHeight = height - margin.top - margin.bottom
const svg = d3.select('#d3-horizontal-chart')
.attr('width', '100%')
@ -42,47 +42,42 @@ const D3HorizontalChart = memo((
.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`)
const percents = ['percents']
const names = data.map(d => d.name)
const stackedData = d3.stack()
//@ts-ignore
.keys(percents)(data)
const xMax = 100
// scales
const x = d3.scaleLinear()
.domain([0, xMax])
.range([0, _width])
.range([0, chartWidth])
const y = d3.scaleBand()
.domain(names)
.range([0, _height])
.padding(0.25)
.range([0, chartHeight])
// axes
const tickValues = [0, 25, 50, 75, 100]
const xAxisTop = d3.axisTop(x)
.tickValues([0, 25, 50, 75, 100])
.tickValues(tickValues)
.tickFormat(d => d + '%')
const xAxisBottom = d3.axisBottom(x)
.tickValues([0, 25, 50, 75, 100])
.tickValues(tickValues)
.tickFormat(d => d + '%')
const yAxisLeft = d3.axisLeft(y)
const gridlines = d3.axisBottom(x)
.tickValues([0, 25, 50, 75, 100])
.tickFormat(d => '')
.tickSize(_height)
.tickValues(tickValues)
.tickFormat(() => '')
.tickSize(chartHeight)
const yAxisRight = d3.axisRight(y)
.ticks(0)
.tickValues([])
.tickFormat(d => '')
.tickFormat(() => '')
svg.append('g')
.attr('transform', `translate(0,0)`)
@ -98,38 +93,30 @@ const D3HorizontalChart = memo((
.call(yAxisLeft)
svg.append('g')
.attr('transform', `translate(0,${_height})`)
.attr('transform', `translate(0,${chartHeight})`)
.call(xAxisBottom)
svg.append('g')
.attr('transform', `translate(${_width},0)`)
.attr('transform', `translate(${chartWidth},0)`)
.call(yAxisRight)
const layers = svg.append('g')
.selectAll('g')
.data(stackedData)
.data(data)
.join('g')
// transition for bars
const duration = 1000
const t = d3.transition()
.duration(duration)
.ease(d3.easeLinear)
layers.each(function() {
d3.select(this)
.selectAll('rect')
//@ts-ignore
.data(d => d)
.data(data)
.join('rect')
.attr('fill', (d, i) => colors ? colors[i] : 'black')
//@ts-ignore
.attr('y', d => y(d.data.name))
.attr('y', d => String(y(d.name)))
.attr('height', y.bandwidth())
//@ts-ignore
.transition(t)
//@ts-ignore
.attr('width', d => d.data.percent >= 0 ? x(d.data.percent) : 0)
.transition()
.duration(1000)
.ease(d3.easeLinear)
.attr('width', d => d.percent >= 0 ? x(d.percent) : 0)
})
return () => {