I am trying to make SVG responsive, so when window is re-sized, my svg will resize as well and fill parent div as it is when viewed first time.
Here is the fiddle - http://jsfiddle.net/nhe613kt/321/
HTML
<div id="myConta">
<div id="myContaList"></div>
</div>
JS
$(window).resize(OwResize);
function OwResize() {
$("#myConta").height(window.innerHeight - (window.innerHeight / 40));
}
var sideRectW = window.innerWidth / 20,
sideRectH = window.innerHeight / 20,
width = window.innerWidth - (window.innerWidth / 50),
height = window.innerHeight - (window.innerHeight / 40),
boxW = (width - sideRectW) / 4,
boxH = (height - sideRectH) / 4,
boxSize = boxW + boxH,
xPos1 = sideRectW,
xPos2 = boxW + sideRectW,
xPos3 = (boxW * 2) + sideRectW,
xPos4 = (boxW * 3) + sideRectW,
yPos1 = 0,
yPos2 = boxH,
yPos3 = boxH * 2,
yPos4 = boxH * 3;
var CreateRect = function (x, y, boxColor, boxId) {
svgContainer.append("rect")
.attr("x", x)
.attr("y", y)
.attr("id", "rectBox" + boxId)
.attr("width", boxW)
.attr("height", boxH)
.attr("fill", boxColor)
.attr("class", "hover_group")
.attr("preserveAspectRatio", "xMaxYMid meet")
.attr("viewBox", "0 0 " + $("#myConta").width() + $("#myConta").height())
.attr("onclick", "alert('haha');");
};
var CreateRectWithLength = function (x, y, w, h, boxColor) {
svgContainer.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", w)
.attr("height", h)
.attr("fill", boxColor);
};
var CreateText = function (x, y, text, textColor, size) {
svgContainer.append("text")
.attr("x", x)
.attr("y", y)
.attr("fill", textColor)
.attr("font-size", size)
.text(text);
};
var CreateText90 = function (x, y, text, textColor, size) {
svgContainer.append("text")
.attr("x", x)
.attr("y", y)
.attr("fill", textColor)
.attr("font-size", size)
.attr("transform", "rotate(-90," + x + 20 + ", " + y + ")")
.text(text);
};
var svgContainer = d3.select("#myConta")
.append("svg")
.attr("id", "myContasvg")
.attr("width", width)
.attr("height", height)
.attr("fill", "#2E2E2E")
.attr("float", "right")
.append("g");
CreateRectWithLength(0, 0, sideRectW, window.innerHeight, "Black");
CreateRectWithLength(0, height - sideRectH, width, sideRectH, "Black");
CreateText90(0, yPos3, "Sales", "white", 16);
CreateText(xPos3, height - sideRectH / 5, "Profit", "white", 16);
CreateText(sideRectW / 2, yPos1 + (boxH / 2), "3", "white", 12);
CreateText(sideRectW / 2, yPos2 + (boxH / 2), "2", "white", 12);
CreateText(sideRectW / 2, yPos3 + (boxH / 2), "1", "white", 12);
CreateText(sideRectW / 2, yPos4 + (boxH / 2), "0", "white", 12);
CreateText(xPos1 + (boxW / 2), height - sideRectH / 2, "0", "white", 12);
CreateText(xPos2 + (boxW / 2), height - sideRectH / 2, "1", "white", 12);
CreateText(xPos3 + (boxW / 2), height - sideRectH / 2, "2", "white", 12);
CreateText(xPos4 + (boxW / 2), height - sideRectH / 2, "3", "white", 12);
CreateRect(xPos1, yPos1, "#C0FC3E", 03);
CreateRect(xPos1, yPos2, "#60FC60", 02);
CreateRect(xPos1, yPos3, "#64FE2E", 01);
CreateRect(xPos1, yPos4, "#00FF00", 00);
CreateRect(xPos2, yPos1, "#F6FF33", 13);
CreateRect(xPos2, yPos2, "#AFFC3B", 12);
CreateRect(xPos2, yPos3, "#00FF00", 11);
CreateRect(xPos2, yPos4, "#64FE2E", 10);
CreateRect(xPos3, yPos1, "#FDB500", 23);
CreateRect(xPos3, yPos2, "#8DB723", 22);
CreateRect(xPos3, yPos3, "#AFFC3B", 21);
CreateRect(xPos3, yPos4, "#60FC60", 20);
CreateRect(xPos4, yPos1, "red", 33);
CreateRect(xPos4, yPos2, "#FDB500", 32);
CreateRect(xPos4, yPos3, "#F6FF33", 31);
CreateRect(xPos4, yPos4, "#C0FC3E", 30);
var rectContainer = d3.selectAll("#rectBox33");
var rectX = rectContainer.attr("x");
console.log(rectX);
Please Note
This is not exact what I am working on, but I tried to make it as close to working example as I could.
What I don't want
I want svg to resize and fill parent div automatically on window size.
I don't know if this is what you were after, but how is this?
Demo fiddle
You need to apply the viewBox and preserveAspectRatio attributes to your SVG. Also if you want the SVG to scale with its parent <div> then you should not set the width and height to fixed values. Instead leave them unset so that the default to the value "100%".
I've created a scatter plot in d3. The problem is that the y axis label does not appear in firefox and chrome (works fine in IE). I've tried doing things like making the svg width 100%, but for some reason the label always gets cut off.
<div id="TimeSeriesChartDiv" style="display: inline; float: right; width: 650px;
height: 415px">
</div>
//Width and height
var w = 600;
var h = 300;
var padding = 30;
var margin = { top: 20, right: 20, bottom: 30, left: 20 };
var df = d3.time.format("%b-%y");
//Create scale functions
var xScale = d3.time.scale()
.domain([d3.min(dataset, function (d) { return d[0]; }), d3.max(dataset, function (d) { return d[0]; })])
.range([padding, w - padding * 2])
.nice(5);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) { return d[1]; })])
.range([h - padding, padding]);
//Define X axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(5)
.tickFormat(df);
//Define Y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
//Create SVG element
var svg = d3.select("#TimeSeriesChartDiv")
.append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom);
//Create X axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(20," + (h - padding) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + 50 + ",0)")
.call(yAxis);
svg.append("text")
.attr("class", "axislabel")
.attr("text-anchor", "end")
.attr("x", w / 2)
.attr("y", h + 8)
.text("Date");
svg.append("text")//-->>this is the text that gets cut off
.attr("class", "axislabel")
.attr("text-anchor", "end")
.attr("x", -100)
.attr("y", -15)
//.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.text(unit);
Any ideas would be much appreciated. Thanks
You are using negative coordinates for your text, which means they get drawn outside the SVG. It seems that IE9 doesn't seem to clip thing to the SVG area, other browsers do. The best solution is to add enough padding to your graph so that your text can be drawn inside the SVG. Disabling the clipping does not seem to be supported in all browsers.
Thanks Jan -- with additional help from:
http://www.d3noob.org/2012/12/adding-axis-labels-to-d3js-graph.html
this worked:
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("class", "axislabel")
.attr("text-anchor", "middle")
.attr("x", 0 - (h / 2))
.attr("y",0)//any negative value here wouldnt display in ff or chrome
.attr("dy", "1em")
.text(unit);
I have 10 legend elements that I want to show in two rows on top of my D3.js chart. I have tried the following
legend.append("rect").attr("width", 20).attr("height", 15).style("fill", function(d) {
return color(d.packageName);
});
legend.append("text").attr("dx", +25).attr("dy", "0.8em").style("text-anchor","front").style("fill", "#666").text(function(d) {
return d.packageName;
});
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 40
};
d3.selectAll(".legend").each(function(d, i) {
return d3.selectAll(".legend").attr("transform", i < 6 ? function(d, i) {
return "translate(" + ((i * 100) + (diameter / 10) - 25) + "," + (+margin.top * 2) +")";
} : function(d, i) {
return "translate(" + ((i * 100) + (diameter / 10) - 25) + "," + (+margin.top * 4) +")";
});
});
My goal was to change the y coordinate if the "i" counter went over 5 so that the legend elements appear in 2 rows of 5. But the above code shows all legend elements in the second row. I'm sure I'm missing something very simple here!
My solution: put everything into the "enter" method, and compute the offsets.
legend = svg.selectAll(".legend").data(data).enter().append("g")
.attr("class", "legend")
.attr( "transform", function(d,i) {
xOff = (i % 4) * 50
yOff = Math.floor(i / 4) * 10
return "translate(" + xOff + "," + yOff + ")"
} );
Consequently, you can delete the entire "selectAll" and "each" portion at the bottom.
Updated Fiddle: http://jsfiddle.net/v7mkg/1/
Side-effect; this particular implementation could create many rows, but that's not at the heart of the issue.
I'm working through a book on data visualization with D3. I'm sorta new to this and I am trying to add axis to my chart. The example code works but for some reason when I try to append an axis class to my SVG element, it won't work.
My code is below:
function draw(data) {
//code
"use strict";
var margin = 50,
width = 700,
height = 300;
var x_extent = d3.extent(data, function(d){return d.collision_with_injury});
var y_extent = d3.extent(data, function(d){return d.dist_between_fail});
var x_scale = d3.scale.linear()
.range([margin, width-margin])
.domain(x_extent);
var y_scale = d3.scale.linear()
.range([height-margin, margin])
.domain(y_extent);
var x_axis = d3.svg.axis().scale("x_scale");
var y_axis = d3.svg.axis().scale("y_scale").orient("left");
d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d){return x_scale(d.collision_with_injury)})
.attr("cy", function(d){return y_scale(d.dist_between_fail)})
.attr("r", 5)
d3.select("svg")
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height-margin) + ")")
.call(x_axis);
d3.select("svg")
.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin +", 0)")
.call(y_axis)
d3.select('.y axis')
.append('text')
.text('mean distance between failure (miles)')
.attr('transform', "rotate (-90, -43, 0) translate(-280)")
d3.select('.x axis')
.append('text')
.text('collisions with injury (per million miles)')
.attr('x', function(){return (width / 2) - margin})
.attr('y', margin/1.5)
}
Class names cannot contain spaces. When you run the code .attr("class", "x axis") you're actually assigning the two classes x and axis to the element. This is not a problem as such, but the selector .y axis doesn't work as you would expect for the same reason. It tries to find an element with class y and an axis tag (as you didn't put a dot in front of it). This fails, as there is no such element.
The easiest way to fix this is probably to simply assign a one-word class, e.g. xAxis. Alternatively, you could change your selector to .y .axis to match elements that have those two classes.
I need to draw a pie chart that's works in IE 8, so I'm using d34raphael.
currently this is my code, which is modified from a d3 pie chart example https://raw.github.com/mbostock/d3/master/examples/pie/pie.html
var width = 300,
height = 300,
outerRadius = Math.min(width, height) / 2,
innerRadius = outerRadius * .6,
data = d3.range(10).map(Math.random),
color = d3.scale.category20(),
donut = d3.layout.pie(),
arc = d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius);
// #chart is a div
var paper = new Raphael($('#chart')[0], width, height);
var svg = d3.raphael(paper);
paper.setStart();
var vis = svg.selectAll('rect')
.data([data])
.enter().append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height);
svg.selectAll('path')
.data(donut)
.enter().append('path')
.attr('fill', function(d, i) { return color(i); })
.attr('d', arc)
.attr('transform', 'translate(' + outerRadius + ',' + outerRadius + ')');
paper.setFinish().transform(['t', 0, 0]);
it crashes when I pass donut into the data function, the bind function inside d3's data function has a group argument. after stepping through the data function, I found that group was undefined. (for me, it crashes on d3.v2.js:4997 bind(group = this[i], value.call(group, group.parentNode.__data__, i));, it tries to reference parentNode on the undefined group) I think this may be related to raphael not supporting the g tag. any Ideas on how i can use the d3 pie layout with d34raphael? Thanks