如何根据屏幕尺寸在D3 js中创建动态y缩放值?

时间:2018-12-26 18:35:11

标签: angularjs d3.js

我使用d3 js创建折线图。当我调整窗口大小而不是滚动条大小时,我需要一种解决方案来更改y比例值。

我添加了以下代码,该代码在我调整屏幕大小时会添加滚动条。当我们为不同的屏幕尺寸调整大小时,我想设计动态y缩放值。 `

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

body { font: 12px Arial;}

path { 
  stroke: steelblue;
  stroke-width: 2;
  fill: none;
}

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

</style>
<body>

<!-- load the d3.js library --> 
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>

// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

// Define the line
var valueline = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });

// Adds the svg canvas
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 + ")");

// Get the data
d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.close = +d.close;
    });

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.date; }));
    y.domain([0, d3.max(data, function(d) { return d.close; })]);

    // Add the valueline path.
    svg.append("path")  
        .attr("class", "line")
        .attr("d", valueline(data));

    // Add the X Axis
    svg.append("g")     
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    // Add the Y Axis
    svg.append("g")     
        .attr("class", "y axis")
        .call(yAxis);

});

</script>
</body>

`

1 个答案:

答案 0 :(得分:0)

我想使用的一种方法是将代码包装在一个函数中(让其称为main()),并在屏幕尺寸改变时重新运行。

在此新main()函数的开始处,删除旧的(现在大小已多余)的svg。

d3.select("#<id of svg>").remove();

然后,使用创建新的y比例尺

var new_width = document.getElementById("<Div ID>").clientWidth;
var new_height = document.getElementById("<Div ID>").clientHeight;

,并在创建新svg时将其应用。 D3应该允许您在创建初始svg之前运行.remove()行。确保在创建svg时添加ID(使用attr("id", "<id of svg>"))。

之后,您可以在调整大小时调用main()函数

d3.select(window).on( "resize", main() );

现在Div的实际大小调整方法将取决于CSS,因此您可以使用{height:50vh}之类的东西。

希望这会有所帮助。

P.S。顺便说一句,为什么要使用D3版本3?我们已经达到v5了:)

相关问题