newcomer newcomer - 6 months ago 15
Javascript Question

D3 histogram is not becoming responsive even after usig preserveAspetRatio

I am making D3 histogram with equal height, but the chart is not becoming responsive even after using the "viewBox" and "preserveaspectRatio". Here is the code I am using

var w = 800;
var h = 80;
var barPadding = 1;
var hello = 10;
var dataset = [ hello, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20 ];

var dataset2 = [ "hey", "you", "know", "that", "you", "are", "an", 18, 15, 13,
11, 12, 15, 20 ];
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("viewBox","0 0 800 80")
.attr("preserveAspectRatio","xMinYMin meet")
.append("g")
.attr("transform", "translate(1,1)");

svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", 0)
.attr("width", 50)
.attr("height", 50)
.attr("rx", 5)
.attr("ry", 5)
.attr("fill", function(d) {
return "rgb(" + (d * 15) + ", " + (d * 5) + ", " + (d * 5) + ")";
})
.style("opacity", function(d){
return 0.05 * (d);
});

svg.selectAll("text")
.data(dataset2)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return i * (w / dataset2.length) + (w / dataset2.length - barPadding) / 2;
})
.attr("y", 18)
.attr("font-family", "sans-serif")
.attr("font-size", "8px")
.attr("fill", "black");


Working fiddle link of the above code is here
https://jsfiddle.net/hawkeye15/m22pyyjL/

Answer

Delete the

 .attr("width",w)
 .attr("height",h)

It will work fine. Below is the fiddle link

https://jsfiddle.net/m22pyyjL/2/

Comments