D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
AlexDaGr8
Full window
Github gist
Just things
<!DOCTYPE html> <body> <script src="https://d3js.org/d3.v5.min.js"></script> <script> var m = 40, w = 960 - m*2, h = 500 - m*2; var svg = d3.select('body').append('svg') .attr('width', w + m*2).attr('height', h + m*2) .append('g') .attr('transform', 'translate(' + [m,m] + ')'); var data = []; for (var i = 0; i< 50; i++) { data.push({ index: i + '', value: Math.floor(Math.random() * 10), radius: Math.floor(Math.random() * 3) }); } data.forEach(function(d) { d.index = +d.index; }) var color = d3.scaleOrdinal(d3.schemeSet2); lineChart(data) barChart(data); function lineChart(data) { var lineChart = svg.append('g') .attr('class', 'lineChart'); var lineW = w/2 - m; var x = d3.scaleLinear() .range([0,lineW]); var y = d3.scaleLinear() .range([h,0]); var radius = d3.scaleLinear() .range([5,10]); var line = d3.line() .x((d,i) => x(i)) .y((d) => y(d.value)); //x.domain([-5,data.length]); x.domain([0, d3.max(data, (d) => d.index)]) y.domain([0,d3.max(data,(d,i) => d.value)]) radius.domain(d3.extent(data,(d) => d.radius)); lineChart.append('g') .attr('class', 'y-axis') .attr('transform', 'translate(' + x(0) + ',0)') .call(d3.axisLeft(y)) lineChart.append('g') .attr('class', 'x-axis') .attr('transform', 'translate(0,' + h + ')') .call(d3.axisBottom(x)) lineChart.append('path') .data([data]) .attr('d', line) .attr('fill', 'none') .attr('stroke', 'black') .attr('stroke-width', 3) lineChart.selectAll('.circle') .data(data) .enter().append('circle') .attr('class', 'circle') .attr('cx', (d) => x(d.index)) .attr('cy', function(d,i) { return y(d.value); }) .attr('r', (d) => radius(d.radius)) .attr('fill', 'white') .attr('stroke', (d) => color(d.radius)) .attr('stroke-width', 5) .on('mouseover', function(a,b,c) { var rects = d3.selectAll('.rect')._groups[0]; d3.select(rects[a.radius]).style('opacity', 0.7); }) .on('mouseout', function(a,b,c) { d3.selectAll('.rect').style('opacity', 1); }) } function barChart(data) { var barW = w/2 - m; var barChart = svg.append('g') .attr('class', 'barChart') .attr('transform', 'translate(' + (barW + m) + ',0)'); var nest = d3.nest() .key((d) => d.radius) .sortKeys(d3.ascending) .entries(data); var y = d3.scaleLinear() .range([h,0]) .domain([0,d3.max(nest, (d) => d.values.length)]); var x = d3.scaleBand() .range([0,barW]) .domain(nest.map((d) => d.key)) .padding(.2); barChart.append('g') .attr('transform', 'translate(0,' + h + ')') .call(d3.axisBottom(x)) barChart.selectAll('rect') .data(nest) .enter().append('rect') .attr('class', 'rect') .attr('x', (d) => x(d.key)) .attr('y', (d) => y(d.values.length)) .attr('width', x.bandwidth()) .attr('height', (d) => h - y(d.values.length)) .attr('fill', (d) => color(d.key)) } </script> </body>
https://d3js.org/d3.v5.min.js