D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ginseng666
Full window
Github gist
simple legend and transition
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>simple legend</title> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> <style> .axis path, line { fill: none; stroke: #d3d3d3; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size:8pt; } .legendaxis text { font-family: sans-serif; font-size:8pt; } .legendaxis path { opacity:0; } </style> </head> <body> <div id="chart"></div> <script type="text/javascript"> var width=500; var height=300; var padding_top=100; var data=[80,45,30,50]; //the data var groups=["red","green","blue","black"]; //the categories, also the fill-colors var labels=["First","Second","Third","Fourth"]; //the labels for the legend var xscale=d3.scale.linear().domain([0,100]).range([5,width-10]); var yscale=d3.scale.ordinal().domain(groups).rangeRoundBands([padding_top,height-20],0.2); var legendscale=d3.scale.ordinal().domain(labels).rangeRoundBands([5,height-(height-padding_top)],0.2); //another ordinal-scale for the legend var xaxis=d3.svg.axis().scale(xscale).orient("bottom"); var legendaxis=d3.svg.axis().scale(legendscale).orient("left").tickSize(0); var svg=d3.select("#chart").append("svg").attr("width",width).attr("height",height); var rect=svg.selectAll("rect").data(data); rect.enter() .append("rect") .attr("x",xscale(0)) .attr("y",function(d,i){return yscale(groups[i]);}) .attr("width",function(d){return xscale(d);}) .attr("height",yscale.rangeBand()) .attr("fill",function(d,i){return groups[i];}); svg.append("g") .attr("class","axis") .attr("transform","translate(0,"+(height-20)+")") .call(xaxis); svg.selectAll(".legend") .data(labels) .enter() .append("rect") .attr("x",width-10) .attr("y",function(d){return legendscale(d);}) .attr("width",10) .attr("height",legendscale.rangeBand()) .attr("fill",function(d,i){return groups[i];}); svg.append("g") .attr("class","legendaxis") .attr("transform","translate("+(width-15)+",0)") .call(legendaxis); xscale.domain([0,200]); //change the domain of the xscale rect.transition() .delay(2000) .duration(1000) .attr("width",function(d){return xscale(d);}); //change the bars svg.selectAll(".axis") //change the ticks on the x-axis .transition() .delay(2000) .duration(1000) .call(xaxis); xscale.range([5,width/2]); //change the range of the xscale rect.transition() .delay(5000) .duration(1000) .attr("width",function(d){return xscale(d);}); //change the bars svg.selectAll(".axis") //change the ticks on the x-axis .transition() .delay(5000) .duration(1000) .call(xaxis); </script> </body> </html>
Modified
http://d3js.org/d3.v3.min.js
to a secure url
https://d3js.org/d3.v3.min.js