Javascript windows.resize()不起作用
大家好,我在我的html body标签中使用d3图表。我想在调整浏览器窗口的大小时自动调整d3图表的宽度和高度 这里我附上了我的代码Javascript windows.resize()不起作用,javascript,d3.js,Javascript,D3.js,大家好,我在我的html body标签中使用d3图表。我想在调整浏览器窗口的大小时自动调整d3图表的宽度和高度 这里我附上了我的代码 d3.min.jsu可以从互联网上获取此js代码 , d3 legend.js (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)r
d3.min.js
u可以从互联网上获取此js代码
,
d3 legend.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var helper = require('./legend');
module.exports = function(){
var scale = d3.scale.linear(),
shape = "rect",
shapeWidth = 15,
shapeHeight = 15,
shapeRadius = 10,
shapePadding = 2,
cells = [5],
labels = [],
useClass = false,
labelFormat = d3.format(".01f"),
labelOffset = 10,
labelAlign = "middle",
labelDelimiter = "to",
orient = "vertical",
path,
legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick");
function legend(svg){
var type = helper.d3_calcType(scale, cells, labels, labelFormat, labelDelimiter);
var cell = svg.selectAll(".cell").data(type.data),
cellEnter = cell.enter().append("g", ".cell").attr("class", "cell").style("opacity", 1e-6);
shapeEnter = cellEnter.append(shape).attr("class", "swatch"),
shapes = cell.select("g.cell " + shape);
//add event handlers
helper.d3_addEvents(cellEnter, legendDispatcher);
cell.exit().transition().style("opacity", 0).remove();
helper.d3_drawShapes(shape, shapes, shapeHeight, shapeWidth, shapeRadius, path);
helper.d3_addText(svg, cellEnter, type.labels)
// sets placement
var text = cell.select("text"),
shapeSize = shapes[0].map( function(d){ return d.getBBox(); });
//sets scale
//everything is fill except for line which is stroke,
if (!useClass){
if (shape == "line"){
shapes.style("stroke", type.feature);
} else {
shapes.style("fill", type.feature);
}
} else {
shapes.attr("class", function(d){ return "swatch " + type.feature(d); });
}
var cellTrans,
textTrans,
textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1;
//positions cells and text
if (orient === "vertical"){
cellTrans = function(d,i) { return "translate(0, " + (i * (shapeSize[i].height + shapePadding)) + ")"; };
textTrans = function(d,i) { return "translate(" + (shapeSize[i].width + shapeSize[i].x +
labelOffset) + "," + (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; };
} else if (orient === "horizontal"){
cellTrans = function(d,i) { return "translate(" + (i * (shapeSize[i].width + shapePadding)) + ",0)"; }
textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign + shapeSize[i].x) +
"," + (shapeSize[i].height + shapeSize[i].y + labelOffset + 8) + ")"; };
}
helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign);
cell.transition().style("opacity", 1);
}
legend.scale = function(_) {
if (!arguments.length) return legend;
scale = _;
return legend;
};
legend.cells = function(_) {
if (!arguments.length) return legend;
if (_.length > 1 || _ >= 2 ){
cells = _;
}
return legend;
};
legend.shape = function(_, d) {
if (!arguments.length) return legend;
if (_ == "rect" || _ == "circle" || _ == "line" || (_ == "path" && (typeof d === 'string')) ){
shape = _;
path = d;
}
return legend;
};
legend.shapeWidth = function(_) {
if (!arguments.length) return legend;
shapeWidth = +_;
return legend;
};
legend.shapeHeight = function(_) {
if (!arguments.length) return legend;
shapeHeight = +_;
return legend;
};
legend.shapeRadius = function(_) {
if (!arguments.length) return legend;
shapeRadius = +_;
return legend;
};
legend.shapePadding = function(_) {
if (!arguments.length) return legend;
shapePadding = +_;
return legend;
};
legend.labels = function(_) {
if (!arguments.length) return legend;
labels = _;
return legend;
};
legend.labelAlign = function(_) {
if (!arguments.length) return legend;
if (_ == "start" || _ == "end" || _ == "middle") {
labelAlign = _;
}
return legend;
};
legend.labelFormat = function(_) {
if (!arguments.length) return legend;
labelFormat = _;
return legend;
};
legend.labelOffset = function(_) {
if (!arguments.length) return legend;
labelOffset = +_;
return legend;
};
legend.labelDelimiter = function(_) {
if (!arguments.length) return legend;
labelDelimiter = _;
return legend;
};
legend.useClass = function(_) {
if (!arguments.length) return legend;
if (_ === true || _ === false){
useClass = _;
}
return legend;
};
legend.orient = function(_){
if (!arguments.length) return legend;
_ = _.toLowerCase();
if (_ == "horizontal" || _ == "vertical") {
orient = _;
}
return legend;
};
d3.rebind(legend, legendDispatcher, "on");
return legend;
};
},{"./legend":2}],2:[function(require,module,exports){
module.exports = {
d3_identity: function (d) {
return d;
},
d3_mergeLabels: function (gen, labels) {
if(labels.length === 0) return gen;
gen = (gen) ? gen : [];
var i = labels.length;
for (; i < gen.length; i++) {
labels.push(gen[i]);
}
return labels;
},
d3_linearLegend: function (scale, cells, labelFormat) {
var data = [];
if (cells.length > 1){
data = cells;
} else {
var domain = scale.domain(),
increment = (domain[domain.length - 1] - domain[0])/(cells - 1),
i = 0;
for (; i < cells; i++){
data.push(labelFormat(domain[0] + i*increment));
}
}
return {data: data,
labels: data,
feature: function(d){ return scale(d); }};
},
d3_quantLegend: function (scale, labelFormat, labelDelimiter) {
var labels = scale.range().map(function(d){
var invert = scale.invertExtent(d),
a = labelFormat(invert[0]),
b = labelFormat(invert[1]);
// if (( (a) && (a.isNan()) && b){
// console.log("in initial statement")
return labelFormat(invert[0]) + " " + labelDelimiter + " " + labelFormat(invert[1]);
// } else if (a || b) {
// console.log('in else statement')
// return (a) ? a : b;
// }
});
return {data: scale.range(),
labels: labels,
feature: this.d3_identity
};
},
d3_ordinalLegend: function (scale) {
return {data: scale.domain(),
labels: scale.domain(),
feature: function(d){ return scale(d); }};
},
d3_drawShapes: function (shape, shapes, shapeHeight, shapeWidth, shapeRadius, path) {
if (shape === "rect"){
shapes.attr("height", shapeHeight).attr("width", shapeWidth);
} else if (shape === "circle") {
shapes.attr("r", shapeRadius)//.attr("cx", shapeRadius).attr("cy", shapeRadius);
} else if (shape === "line") {
shapes.attr("x1", 0).attr("x2", shapeWidth).attr("y1", 0).attr("y2", 0);
} else if (shape === "path") {
shapes.attr("d", path);
}
},
d3_addText: function (svg, enter, labels){
enter.append("text").attr("class", "label");
svg.selectAll("g.cell text").data(labels).text(this.d3_identity);
},
d3_calcType: function (scale, cells, labels, labelFormat, labelDelimiter){
var type = scale.ticks ?
this.d3_linearLegend(scale, cells, labelFormat) : scale.invertExtent ?
this.d3_quantLegend(scale, labelFormat, labelDelimiter) : this.d3_ordinalLegend(scale);
type.labels = this.d3_mergeLabels(type.labels, labels);
return type;
},
d3_placement: function (orient, cell, cellTrans, text, textTrans, labelAlign) {
cell.attr("transform", cellTrans);
text.attr("transform", textTrans);
if (orient === "horizontal"){
text.style("text-anchor", labelAlign);
}
},
d3_addEvents: function(cells, dispatcher){
var _ = this;
cells.on("mouseover.legend", function (d) { _.d3_cellOver(dispatcher, d, this); })
.on("mouseout.legend", function (d) { _.d3_cellOut(dispatcher, d, this); })
.on("click.legend", function (d) { _.d3_cellClick(dispatcher, d, this); });
},
d3_cellOver: function(cellDispatcher, d, obj){
cellDispatcher.cellover.call(obj, d);
},
d3_cellOut: function(cellDispatcher, d, obj){
cellDispatcher.cellout.call(obj, d);
},
d3_cellClick: function(cellDispatcher, d, obj){
cellDispatcher.cellclick.call(obj, d);
}
}
},{}],3:[function(require,module,exports){
var helper = require('./legend');
module.exports = function(){
var scale = d3.scale.linear(),
shape = "rect",
shapeWidth = 15,
shapePadding = 2,
cells = [5],
labels = [],
useStroke = false,
labelFormat = d3.format(".01f"),
labelOffset = 10,
labelAlign = "middle",
labelDelimiter = "to",
orient = "vertical",
path,
legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick");
function legend(svg){
var type = helper.d3_calcType(scale, cells, labels, labelFormat, labelDelimiter);
var cell = svg.selectAll(".cell").data(type.data),
cellEnter = cell.enter().append("g", ".cell").attr("class", "cell").style("opacity", 1e-6);
shapeEnter = cellEnter.append(shape).attr("class", "swatch"),
shapes = cell.select("g.cell " + shape);
//add event handlers
helper.d3_addEvents(cellEnter, legendDispatcher);
cell.exit().transition().style("opacity", 0).remove();
//creates shape
if (shape === "line"){
helper.d3_drawShapes(shape, shapes, 0, shapeWidth);
shapes.attr("stroke-width", type.feature);
} else {
helper.d3_drawShapes(shape, shapes, type.feature, type.feature, type.feature, path);
}
helper.d3_addText(svg, cellEnter, type.labels)
//sets placement
var text = cell.select("text"),
shapeSize = shapes[0].map(
function(d, i){
var bbox = d.getBBox()
var stroke = scale(type.data[i]);
if (shape === "line" && orient === "horizontal") {
bbox.height = bbox.height + stroke;
} else if (shape === "line" && orient === "vertical"){
bbox.width = bbox.width;
}
return bbox;
});
var maxH = d3.max(shapeSize, function(d){ return d.height + d.y; }),
maxW = d3.max(shapeSize, function(d){ return d.width + d.x; });
var cellTrans,
textTrans,
textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1;
//positions cells and text
if (orient === "vertical"){
cellTrans = function(d,i) {
var height = d3.sum(shapeSize.slice(0, i + 1 ), function(d){ return d.height; });
return "translate(0, " + (height + i*shapePadding) + ")"; };
textTrans = function(d,i) { return "translate(" + (maxW + labelOffset) + "," +
(shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; };
} else if (orient === "horizontal"){
cellTrans = function(d,i) {
var width = d3.sum(shapeSize.slice(0, i + 1 ), function(d){ return d.width; });
return "translate(" + (width + i*shapePadding) + ",0)"; };
textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign + shapeSize[i].x) + "," +
(maxH + labelOffset ) + ")"; };
}
helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign);
cell.transition().style("opacity", 1);
}
legend.scale = function(_) {
if (!arguments.length) return legend;
scale = _;
return legend;
};
legend.cells = function(_) {
if (!arguments.length) return legend;
if (_.length > 1 || _ >= 2 ){
cells = _;
}
return legend;
};
legend.shape = function(_, d) {
if (!arguments.length) return legend;
if (_ == "rect" || _ == "circle" || _ == "line" ){
shape = _;
path = d;
}
return legend;
};
legend.shapeWidth = function(_) {
if (!arguments.length) return legend;
shapeWidth = +_;
return legend;
};
legend.shapePadding = function(_) {
if (!arguments.length) return legend;
shapePadding = +_;
return legend;
};
legend.labels = function(_) {
if (!arguments.length) return legend;
labels = _;
return legend;
};
legend.labelAlign = function(_) {
if (!arguments.length) return legend;
if (_ == "start" || _ == "end" || _ == "middle") {
labelAlign = _;
}
return legend;
};
legend.labelFormat = function(_) {
if (!arguments.length) return legend;
labelFormat = _;
return legend;
};
legend.labelOffset = function(_) {
if (!arguments.length) return legend;
labelOffset = +_;
return legend;
};
legend.labelDelimiter = function(_) {
if (!arguments.length) return legend;
labelDelimiter = _;
return legend;
};
legend.orient = function(_){
if (!arguments.length) return legend;
_ = _.toLowerCase();
if (_ == "horizontal" || _ == "vertical") {
orient = _;
}
return legend;
};
d3.rebind(legend, legendDispatcher, "on");
return legend;
};
},{"./legend":2}],4:[function(require,module,exports){
var helper = require('./legend');
module.exports = function(){
var scale = d3.scale.linear(),
shape = "path",
shapeWidth = 15,
shapeHeight = 15,
shapeRadius = 10,
shapePadding = 5,
cells = [5],
labels = [],
useClass = false,
labelFormat = d3.format(".01f"),
labelAlign = "middle",
labelOffset = 10,
labelDelimiter = "to",
orient = "vertical",
legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick");
function legend(svg){
var type = helper.d3_calcType(scale, cells, labels, labelFormat, labelDelimiter);
var cell = svg.selectAll(".cell").data(type.data),
cellEnter = cell.enter().append("g", ".cell").attr("class", "cell").style("opacity", 1e-6);
shapeEnter = cellEnter.append(shape).attr("class", "swatch"),
shapes = cell.select("g.cell " + shape);
//add event handlers
helper.d3_addEvents(cellEnter, legendDispatcher);
//remove old shapes
cell.exit().transition().style("opacity", 0).remove();
helper.d3_drawShapes(shape, shapes, shapeHeight, shapeWidth, shapeRadius, type.feature);
helper.d3_addText(svg, cellEnter, type.labels)
// sets placement
var text = cell.select("text"),
shapeSize = shapes[0].map( function(d){ return d.getBBox(); });
var maxH = d3.max(shapeSize, function(d){ return d.height; }),
maxW = d3.max(shapeSize, function(d){ return d.width; });
var cellTrans,
textTrans,
textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1;
//positions cells and text
if (orient === "vertical"){
cellTrans = function(d,i) { return "translate(0, " + (i * (maxH + shapePadding)) + ")"; };
textTrans = function(d,i) { return "translate(" + (maxW + labelOffset) + "," +
(shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; };
} else if (orient === "horizontal"){
cellTrans = function(d,i) { return "translate(" + (i * (maxW + shapePadding)) + ",0)"; };
textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign + shapeSize[i].x) + "," +
(maxH + labelOffset ) + ")"; };
}
helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign);
cell.transition().style("opacity", 1);
}
legend.scale = function(_) {
if (!arguments.length) return legend;
scale = _;
return legend;
};
legend.cells = function(_) {
if (!arguments.length) return legend;
if (_.length > 1 || _ >= 2 ){
cells = _;
}
return legend;
};
legend.shapePadding = function(_) {
if (!arguments.length) return legend;
shapePadding = +_;
return legend;
};
legend.labels = function(_) {
if (!arguments.length) return legend;
labels = _;
return legend;
};
legend.labelAlign = function(_) {
if (!arguments.length) return legend;
if (_ == "start" || _ == "end" || _ == "middle") {
labelAlign = _;
}
return legend;
};
legend.labelFormat = function(_) {
if (!arguments.length) return legend;
labelFormat = _;
return legend;
};
legend.labelOffset = function(_) {
if (!arguments.length) return legend;
labelOffset = +_;
return legend;
};
legend.labelDelimiter = function(_) {
if (!arguments.length) return legend;
labelDelimiter = _;
return legend;
};
legend.orient = function(_){
if (!arguments.length) return legend;
_ = _.toLowerCase();
if (_ == "horizontal" || _ == "vertical") {
orient = _;
}
return legend;
};
d3.rebind(legend, legendDispatcher, "on");
return legend;
};
},{"./legend":2}],5:[function(require,module,exports){
d3.legend = {
color: require('./color'),
size: require('./size'),
symbol: require('./symbol')
};
},{"./color":1,"./size":3,"./symbol":4}]},{},[5]);
legend code ending here
但这对我不起作用。当我按下刷新按钮时,只有它会调整大小,任何人都可以解决我的问题。一个函数必须返回一些工作
myFunction()
仅捕捉窗口内部高度和宽度,但不返回。
将此替换为您的函数:
function myFunction() {
var m = new Array();
m['w'] = window.outerWidth;
m['h'] = window.outerHeight;
return m;
}
然后得到如下值:
var m = myFunction();
currentWidth = m['w'];
currentHeight = m['h'];
如果这不是您想要的,请让我知道函数必须返回一些东西才能工作
myFunction()
仅捕捉窗口内部高度和宽度,但不返回。
将此替换为您的函数:
function myFunction() {
var m = new Array();
m['w'] = window.outerWidth;
m['h'] = window.outerHeight;
return m;
}
然后得到如下值:
var m = myFunction();
currentWidth = m['w'];
currentHeight = m['h'];
如果这不是您想要的,请让我知道使用下面的代码触发调整图表大小
window.onresize = function(){ //logic to resize the chart }
或
根据要求,我已修改了图表的代码。以下是更新的html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Example</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="d3-legend.js"></script>
<meta name="viewport" content="width=device-width"/>
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis text {
font-family: 'Open Sans', sans-serif;
font-size: 12pt;
}
.axis .label {
font-size: 20pt;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.color-legend text {
font-family: 'Open Sans', sans-serif;
font-size: 12pt;
}
rect:hover {
fill: #3EBCE6;
}
.toolTip {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: absolute;
display: none;
width: auto;
height: auto;
background: none repeat scroll 0 0 white;
border: 0 none;
border-radius: 8px 8px 8px 8px;
box-shadow: -3px 3px 15px #888888;
color: black;
font: 12px sans-serif;
padding: 5px;
text-align: center;
}
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg");
var margin = {left: 50, top: 30, right: 30, bottom: 40};
var barPadding = 0.2;
var xColumn = "Building";
var yColumn = "Total";
var colorColumn = "Type";
var xAxisShift = 150;
var layerColumn, xScale, yScale, xAxisG, yAxisG, colorLegendG, xAxis, yAxis, g;
var colorScale = d3.scale.category10();
var colorLegend = d3.legend.color()
.scale(colorScale)
.shapePadding(2)
.shapeWidth(15)
.shapeHeight(15)
.labelOffset(4);
function recalculateDimensions() {
var outerWidth = window.innerWidth - 30;
var outerHeight = window.innerHeight - 80;
layerColumn = colorColumn;
var innerWidth = outerWidth - margin.left - margin.right;
var innerHeight = outerHeight - margin.top - margin.bottom;
svg.attr("width", outerWidth)
.attr("height", outerHeight + 50);
g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")");
xAxisG = g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + innerHeight + ")");
yAxisG = g.append("g")
.attr("class", "y axis");
colorLegendG = g.append("g")
.attr("class", "color-legend")
.attr("transform", "translate(" + (outerWidth - 200) + ", 0)");
xScale = d3.scale.ordinal().rangeBands([0, innerWidth - xAxisShift], barPadding);
yScale = d3.scale.linear().range([innerHeight, 0]);
xAxis = d3.svg.axis().scale(xScale).orient("bottom")
.outerTickSize(0);
yAxis = d3.svg.axis().scale(yScale).orient("left")
.ticks(7)
.tickFormat(d3.format("s"))
.outerTickSize(0);
}
recalculateDimensions();
function render(data) {
var nested = d3.nest()
.key(function (d) {
return d[layerColumn];
})
.entries(data)
var stack = d3.layout.stack()
.y(function (d) {
return d[yColumn];
})
.values(function (d) {
return d.values;
});
var layers = stack(nested);
//tool tip for div class
var divTooltip = d3.select("body").append("div").attr("class", "toolTip");
xScale.domain(layers[0].values.map(function (d) {
return d[xColumn];
}));
yScale.domain([
0,
d3.max(layers, function (layer) {
return d3.max(layer.values, function (d) {
return d.y;
});
})
]);
colorScale.domain(layers.map(function (layer) {
return layer.key;
}));
xAxisG.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.5em")
.attr("dy", "-.0em")
.attr("transform", function (d) {
return "rotate(-45)"
});
yAxisG.call(yAxis);
var layers = g.selectAll(".layer").data(layers);
layers.enter().append("g").attr("class", "layer");
layers.exit().remove();
layers.style("fill", function (d) {
return colorScale(d.key);
});
var bars = layers.selectAll("rect").data(function (d) {
return d.values;
});
var barWidth = xScale.rangeBand() / colorScale.domain().length;
bars.enter()
.append("rect")
bars.exit().remove();
bars
.attr("x", function (d, i, j) {
return xScale(d[xColumn]) + barWidth * j;
})
.attr("y", function (d) {
return yScale(d.y);
})
.attr("width", barWidth)
.attr("height", function (d) {
return innerHeight - yScale(d.y) - xAxisShift;
})
//toolTip mouse hover on bar
bars.on("mousemove", function (d) {
divTooltip.style("left", d3.event.pageX + 10 + "px");
divTooltip.style("top", d3.event.pageY - 25 + "px");
divTooltip.style("display", "inline-block");
var x = d3.event.pageX,
y = d3.event.pageY
var elements = document.querySelectorAll(':hover');
l = elements.length
l = l - 1
elementData = function (d) {
return d
}
divTooltip.html((d.Building) + "<br>" + "Type:" + d.Type + "<br>" + "Small:" + d.Small + "<br>" + "Medium:" + d.Medium + "<br>" + "Large:" + d.Large + "<br>" + "Total:" + d.Total + "<br>");
})
//tooltip mouse release on bar
bars.on("mouseout", function (d) {
divTooltip.style("display", "none");
})
//legend
.text(function (d) {
return d.VALUE;
});
colorLegendG.call(colorLegend);
}
function type(d) {
d.Total = +d.Total;
return d;
}
d3.csv("D3.csv", type, function(data){
chartData = data;
render(chartData);
});
// Define the div for the tooltip
window.onresize = function () {
d3.select('svg>g').remove();
recalculateDimensions();
render(chartData);
}
</script>
</body>
</html>
D3示例
身体{
字体:12px Arial;
}
路径{
笔画:钢蓝;
笔画宽度:2;
填充:无;
}
.轴文本{
字体系列:“开放式Sans”,无衬线;
字号:12号;
}
.axis.标签{
字号:20pt;
}
.轴路径,.轴线{
填充:无;
行程:#000;
形状渲染:边缘清晰;
}
.彩色图例文本{
字体系列:“开放式Sans”,无衬线;
字号:12号;
}
矩形:悬停{
填充:#3EBCE6;
}
.工具提示{
字体系列:“Helvetica Neue”,Helvetica,Arial,无衬线;
位置:绝对位置;
显示:无;
宽度:自动;
高度:自动;
背景:无重复滚动0 0白色;
边界:0无;
边界半径:8px 8px 8px 8px;
盒影:-3px 3px 15px#8888888;
颜色:黑色;
字体:12px无衬线;
填充物:5px;
文本对齐:居中;
}
var svg=d3.选择(“主体”).追加(“svg”);
var-margin={左:50,上:30,右:30,下:40};
var=0.2;
var xColumn=“建筑”;
var yColumn=“总计”;
var colorColumn=“Type”;
var xAxisShift=150;
var layerColumn、xScale、yScale、xAxisG、yAxisG、colorLegendG、xAxis、yAxis、g;
var colorScale=d3.scale.category10();
var colorLegend=d3.legend.color()
.刻度(彩色刻度)
.形状添加(2)
.形状宽度(15)
.shapeHeight(15)
.标签偏移(4);
函数重新计算维度(){
var outerWidth=window.innerWidth-30;
var outerHeight=window.innerHeight-80;
layerColumn=颜色列;
var innerWidth=outerWidth-margin.left-margin.right;
var innerHeight=outerHeight-margin.top-margin.bottom;
svg.attr(“宽度”,外层宽度)
.attr(“高度”,外光+50);
g=svg.append(“g”)
.attr(“变换”、“平移”(+margin.left+)、“+margin.right+”);
xAxisG=g.append(“g”)
.attr(“类”、“x轴”)
.attr(“变换”、“平移(0)”+innerHeight+”);
yAxisG=g.append(“g”)
.attr(“类”、“y轴”);
colorLegendG=g.append(“g”)
.attr(“类别”、“颜色图例”)
.attr(“transform”、“translate”(+(外径-200)+”,0)”);
xScale=d3.scale.ordinal().rangeBands([0,innerWidth-xAxisShift],barPadding);
yScale=d3.scale.linear().范围([innerHeight,0]);
xAxis=d3.svg.axis().scale(xScale.orient(“底部”)
.outerTickSize(0);
yAxis=d3.svg.axis().scale(yScale.orient(“左”)
.滴答声(7)
.tickFormat(d3.format(“s”))
.outerTickSize(0);
}
重新计算维度();
函数渲染(数据){
var nested=d3.nest()
.键(功能(d){
返回d[层列];
})
.条目(数据)
var stack=d3.layout.stack()
.y(功能(d){
返回d[y列];
})
.价值观(功能(d){
返回d值;
});
变量层=堆栈(嵌套);
//div类的工具提示
var divTooltip=d3.select(“body”).append(“div”).attr(“class”,“toolTip”);
xScale.domain(层[0].values.map(函数(d)){
返回d[xColumn];
}));
yScale.domain([
0,
d3.最大值(层、功能(层){
返回d3.max(层值,函数(d){
返回d.y;
});
})
]);
colorScale.domain(layers.map)(函数(层){
返回layer.key;
}));
xAxisG.call(xAxis)
.selectAll(“文本”)
.style(“文本锚定”、“结束”)
.attr(“dx”,“-.5em”)
.attr(“dy”,“-.0em”)
.attr(“转换”,函数(d){
返回“旋转(-45)”
});
yAxisG.call(yAxis);
var layers=g.selectAll(“.layer”)。数据(层);
layers.enter().append(“g”).attr(“类”、“层”);
layers.exit().remove();
图层。样式(“填充”,功能(d){
返回色标(d键);
});
变量条=层。选择全部(“rect”)。数据(函数(d){
返回d值;
});
var barWidth=xScale.rangeBand()/colorScale.domain().length;
输入()
.append(“rect”)
bar.exit().remove();
酒吧
.attr(“x”,函数(d,i,j){
返回xScale(d[xColumn])+条宽*j;
})
.attr(“y”,函数(d){
返回y刻度(d.y);
})
.attr(“宽度”,barWidth)
.attr(“高度”,功能(d){
返回内部高度-yScale(d.y)-xAxisShift;
})
//工具提示鼠标悬停在工具栏上
打开(“鼠标移动”,函数(d){
divTooltip.style(“左”,d3.event.pageX+10+“px”);
divTooltip.style(“top”,d3.event.pageY-25+“px”);
样式(“显示”、“内联块”);
var x=d3.event.pageX,
y=d3.event.pageY
var elements=document.querySelectorAll(':hover');
l=元素长度
l=l-1
elementData=函数(d){
返回d
}
D
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Example</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="d3-legend.js"></script>
<meta name="viewport" content="width=device-width"/>
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis text {
font-family: 'Open Sans', sans-serif;
font-size: 12pt;
}
.axis .label {
font-size: 20pt;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.color-legend text {
font-family: 'Open Sans', sans-serif;
font-size: 12pt;
}
rect:hover {
fill: #3EBCE6;
}
.toolTip {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: absolute;
display: none;
width: auto;
height: auto;
background: none repeat scroll 0 0 white;
border: 0 none;
border-radius: 8px 8px 8px 8px;
box-shadow: -3px 3px 15px #888888;
color: black;
font: 12px sans-serif;
padding: 5px;
text-align: center;
}
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg");
var margin = {left: 50, top: 30, right: 30, bottom: 40};
var barPadding = 0.2;
var xColumn = "Building";
var yColumn = "Total";
var colorColumn = "Type";
var xAxisShift = 150;
var layerColumn, xScale, yScale, xAxisG, yAxisG, colorLegendG, xAxis, yAxis, g;
var colorScale = d3.scale.category10();
var colorLegend = d3.legend.color()
.scale(colorScale)
.shapePadding(2)
.shapeWidth(15)
.shapeHeight(15)
.labelOffset(4);
function recalculateDimensions() {
var outerWidth = window.innerWidth - 30;
var outerHeight = window.innerHeight - 80;
layerColumn = colorColumn;
var innerWidth = outerWidth - margin.left - margin.right;
var innerHeight = outerHeight - margin.top - margin.bottom;
svg.attr("width", outerWidth)
.attr("height", outerHeight + 50);
g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")");
xAxisG = g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + innerHeight + ")");
yAxisG = g.append("g")
.attr("class", "y axis");
colorLegendG = g.append("g")
.attr("class", "color-legend")
.attr("transform", "translate(" + (outerWidth - 200) + ", 0)");
xScale = d3.scale.ordinal().rangeBands([0, innerWidth - xAxisShift], barPadding);
yScale = d3.scale.linear().range([innerHeight, 0]);
xAxis = d3.svg.axis().scale(xScale).orient("bottom")
.outerTickSize(0);
yAxis = d3.svg.axis().scale(yScale).orient("left")
.ticks(7)
.tickFormat(d3.format("s"))
.outerTickSize(0);
}
recalculateDimensions();
function render(data) {
var nested = d3.nest()
.key(function (d) {
return d[layerColumn];
})
.entries(data)
var stack = d3.layout.stack()
.y(function (d) {
return d[yColumn];
})
.values(function (d) {
return d.values;
});
var layers = stack(nested);
//tool tip for div class
var divTooltip = d3.select("body").append("div").attr("class", "toolTip");
xScale.domain(layers[0].values.map(function (d) {
return d[xColumn];
}));
yScale.domain([
0,
d3.max(layers, function (layer) {
return d3.max(layer.values, function (d) {
return d.y;
});
})
]);
colorScale.domain(layers.map(function (layer) {
return layer.key;
}));
xAxisG.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.5em")
.attr("dy", "-.0em")
.attr("transform", function (d) {
return "rotate(-45)"
});
yAxisG.call(yAxis);
var layers = g.selectAll(".layer").data(layers);
layers.enter().append("g").attr("class", "layer");
layers.exit().remove();
layers.style("fill", function (d) {
return colorScale(d.key);
});
var bars = layers.selectAll("rect").data(function (d) {
return d.values;
});
var barWidth = xScale.rangeBand() / colorScale.domain().length;
bars.enter()
.append("rect")
bars.exit().remove();
bars
.attr("x", function (d, i, j) {
return xScale(d[xColumn]) + barWidth * j;
})
.attr("y", function (d) {
return yScale(d.y);
})
.attr("width", barWidth)
.attr("height", function (d) {
return innerHeight - yScale(d.y) - xAxisShift;
})
//toolTip mouse hover on bar
bars.on("mousemove", function (d) {
divTooltip.style("left", d3.event.pageX + 10 + "px");
divTooltip.style("top", d3.event.pageY - 25 + "px");
divTooltip.style("display", "inline-block");
var x = d3.event.pageX,
y = d3.event.pageY
var elements = document.querySelectorAll(':hover');
l = elements.length
l = l - 1
elementData = function (d) {
return d
}
divTooltip.html((d.Building) + "<br>" + "Type:" + d.Type + "<br>" + "Small:" + d.Small + "<br>" + "Medium:" + d.Medium + "<br>" + "Large:" + d.Large + "<br>" + "Total:" + d.Total + "<br>");
})
//tooltip mouse release on bar
bars.on("mouseout", function (d) {
divTooltip.style("display", "none");
})
//legend
.text(function (d) {
return d.VALUE;
});
colorLegendG.call(colorLegend);
}
function type(d) {
d.Total = +d.Total;
return d;
}
d3.csv("D3.csv", type, function(data){
chartData = data;
render(chartData);
});
// Define the div for the tooltip
window.onresize = function () {
d3.select('svg>g').remove();
recalculateDimensions();
render(chartData);
}
</script>
</body>
</html>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 525 365" preserveAspectRatio="xMidYMin slice"></svg>