d3.js - Mirror d3 graph horizontally in JavaScript/html -
i'm trying flip graph in js without changing axis. javascript isn't specialty , after googling 4 hours i'm starting think isn't possible. can point me in right direction please?
var width = 960, height = 500; d3.json("data2.json", function(error, heatmap) { var dx = heatmap[0].length, dy = heatmap.length; // fix aspect ratio. // var ka = dy / dx, kb = height / width; // if (ka < kb) height = width * ka; // else width = height / ka; var x = d3.scale.linear() .domain([0, dx]) .range([0, width]); var y = d3.scale.linear() .domain([0, dy]) .range([height, 0]); var color = d3.scale.linear() .domain([null, 0, 30, 60, 90, 120]) .range(["#ffffff", "#ff0000", "#ff9933", "#ffff00", "#99ff33", "#00ff00"]); var xaxis = d3.svg.axis() .scale(x) .orient("top") .ticks(20); var yaxis = d3.svg.axis() .scale(y) .orient("right"); d3.select("body").append("canvas") .attr("width", dx) .attr("height", dy) .style("width", width + "px") .style("height", height + "px") .call(drawimage); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xaxis) .call(removezero); svg.append("g") .attr("class", "y axis") .call(yaxis) .call(removezero); function drawimage(canvas) { var context = canvas.node().getcontext("2d"), image = context.createimagedata(dx, dy); (var y = 0, p = -1; y < dy; ++y) { (var x = 0; x < dx; ++x) { var c = d3.rgb(color(heatmap[y][x])); image.data[++p] = c.r; image.data[++p] = c.g; image.data[++p] = c.b; image.data[++p] = 255; } } context.putimagedata(image, 0, 0); } function removezero(axis) { axis.selectall("g").filter(function(d) { return !d; }).remove(); } });
i see you're not using d3 part of code makes image itself. in nested loops, when you're manually producing bitmap image, can traverse data in reverse. instead of indexing row heatmap[y]
directly on x
, should index on dx - x - 1
, column number counting right.
as aside, seems little strange mixing svg , canvas drawing techniques here. depending on how data you're showing, may valuable draw heatmap svg well, allow use single api draw chart , enable interactions well. alternatively, go drawing whole thing on canvas, if static image more appropriate, instance if scale of data massive.
Comments
Post a Comment