forked from mbostock's block: Wrapping Long Labels
xxxxxxxxxx
<meta charset="utf-8">
<style>
.bar-pe {
fill: #0075ea;
}
.bar-to {
fill: #008e2d;
}
.bar-pa {
fill: #ffa500;
}
.bar-re {
fill: #FF0000;
}
.bar-pe:hover {
fill: #56aafe;
}
.bar-to:hover {
fill: #00BC3C;
}
.bar-pa:hover {
fill: #ffbb3d;
}
.bar-re:hover {
fill: #ff1e1e;
}
/*tooltip*/
.show {
display: block;
}
.hidden {
display: none;
}
.tooltip {
background-color: #333;
padding: 4px 8px;
position: absolute;
color: #fff;
opacity: 0.8;
z-index: 100;
}
.title {
font: bold 14px "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
stroke-dasharray: 2px 2px;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var puntos = [
{name: "Pendientes", value: 0.40},
{name: "Totales", value: 0.0667},
{name: "Parciales", value: 0.0667},
{name: "Rechazados", value: 0.0}
];
var margin = {top: 80, right: 180, bottom: 80, left: 180},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1, 0.3);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(8, "%");
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//EL GRÁFICO
x.domain(puntos.map(function(d) { return d.name; }));
y.domain([0, d3.max(puntos, function(d) { return d.value; })]);
svg.append("text")
.attr("class", "title")
.attr("x", (150), (puntos[0].name))
.attr("y", -30)
.text("Porcentaje de las entregas según su estado");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll(".tick text")
.call(wrap, x.rangeBand());
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll(".bar")
.data(puntos)
.enter().append("rect")
.attr("class", function(d) {
if(d.name == "Pendientes") { return "bar-pe";}
else if(d.name == "Totales") { return "bar-to";}
else if(d.name == "Parciales") { return "bar-pa";}
else if(d.name == "Rechazados") { return "bar-re";}
})
.attr("x", function(d) { return x(d.name); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.on('mouseover', function(d){
d3.select("#major").text(d.key);
tooltip.transition()
.duration(500)
.style("opacity", 1);
tooltip.html((d.value * 100) + "%")
.style("left", (d3.event.pageX - 25) + "px")
.style("top", (d3.event.pageY - 50) + "px");
})
.on('mousemove', function (d) {
tooltip.style("top", (d3.event.pageY - 50) + 'px');
tooltip.style("left", (d3.event.pageX - 25) + 'px');
})
.on('mouseout', function(d){
d3.select("#major").text("Mouse over");
tooltip.transition()
.duration(500)
.style("opacity", 0);
})
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
function type(d) {
d.value = +d.value;
return d;
}
// Set-up the export button
d3.select('#saveButton').on('click', function(){
var svgString = getSVGString(svg.node());
svgString2Image( svgString, 2*width, 2*height, 'png', save ); // passes Blob and filesize String to the callback
function save( dataBlob, filesize ){
saveAs( dataBlob, 'D3 vis exported to PNG.png' ); // FileSaver.js function
}
});
// Below are the functions that handle actual exporting:
// getSVGString ( svgNode ) and svgString2Image( svgString, width, height, format, callback )
function getSVGString( svgNode ) {
svgNode.setAttribute('xlink', 'https://www.w3.org/1999/xlink');
var cssStyleText = getCSSStyles( svgNode );
appendCSS( cssStyleText, svgNode );
var serializer = new XMLSerializer();
var svgString = serializer.serializeToString(svgNode);
svgString = svgString.replace(/(\w+)?:?xlink=/g, 'xmlns:xlink='); // Fix root xlink without namespace
svgString = svgString.replace(/NS\d+:href/g, 'xlink:href'); // Safari NS namespace fix
return svgString;
function getCSSStyles( parentElement ) {
var selectorTextArr = [];
// Add Parent element Id and Classes to the list
selectorTextArr.push( '#'+parentElement.id );
for (var c = 0; c < parentElement.classList.length; c++)
if ( !contains('.'+parentElement.classList[c], selectorTextArr) )
selectorTextArr.push( '.'+parentElement.classList[c] );
// Add Children element Ids and Classes to the list
var nodes = parentElement.getElementsByTagName("*");
for (var i = 0; i < nodes.length; i++) {
var id = nodes[i].id;
if ( !contains('#'+id, selectorTextArr) )
selectorTextArr.push( '#'+id );
var classes = nodes[i].classList;
for (var c = 0; c < classes.length; c++)
if ( !contains('.'+classes[c], selectorTextArr) )
selectorTextArr.push( '.'+classes[c] );
}
// Extract CSS Rules
var extractedCSSText = "";
for (var i = 0; i < document.styleSheets.length; i++) {
var s = document.styleSheets[i];
try {
if(!s.cssRules) continue;
} catch( e ) {
if(e.name !== 'SecurityError') throw e; // for Firefox
continue;
}
var cssRules = s.cssRules;
for (var r = 0; r < cssRules.length; r++) {
if ( contains( cssRules[r].selectorText, selectorTextArr ) )
extractedCSSText += cssRules[r].cssText;
}
}
return extractedCSSText;
function contains(str,arr) {
return arr.indexOf( str ) === -1 ? false : true;
}
}
function appendCSS( cssText, element ) {
var styleElement = document.createElement("style");
styleElement.setAttribute("type","text/css");
styleElement.innerHTML = cssText;
var refNode = element.hasChildNodes() ? element.children[0] : null;
element.insertBefore( styleElement, refNode );
}
}
function svgString2Image( svgString, width, height, format, callback ) {
var format = format ? format : 'png';
var imgsrc = 'data:image/svg+xml;base64,'+ btoa( unescape( encodeURIComponent( svgString ) ) ); // Convert SVG string to data URL
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
var image = new Image();
image.onload = function() {
context.clearRect ( 0, 0, width, height );
context.drawImage(image, 0, 0, width, height);
canvas.toBlob( function(blob) {
var filesize = Math.round( blob.length/1024 ) + ' KB';
if ( callback ) callback( blob, filesize );
});
};
image.src = imgsrc;
}
</script>
<div>
<button id='saveButton'>Export my D3 visualization to PNG</button>
</div>
</body>
https://d3js.org/d3.v3.min.js