我正在尝试使用leaflet.js和d3.js可视化地图和图表。我想让视图设备兼容。但我的图表和地图不兼容设备。显示简单条形图的代码如下:
function updateCharts(data){
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 400 - margin.left - margin.right,
height = 250 - margin.top;
var x = d3.scale.ordinal().rangeRoundBands([ 0, width ], .05);
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(20);
x.domain(data.map(function(d) { return d.time; }));
y.domain([0, d3.max(data, function(d) { return d.speed1; })]);
var svg=d3.select("#bar").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 + ")");
var transition = svg.transition().duration(750), delay = function(d, i) {
return i * 50;
};
svg.append("text").attr("x", width / 2).attr("y", 0).style("text-anchor",
"middle").text("Speed of Lane1 Vs Time");
//Create X axis label
svg.append("text")
.attr("x", width / 2 )
.attr("y", height + margin.bottom)
.style("text-anchor", "middle")
.text("Time");
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0-margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Speed");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.attr("x",5)
.style("text-anchor", "middle");
svg.selectAll("rect")
.data(data)
.enter().append("rect").transition().delay(0)
.style("fill", "red")
.attr("x", function(d,i) { return x(d.time); }) //v
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.speed1); })
.attr("height", function(d) { return height - y(d.speed1); });
//function(d){return " "+d.datetime;}
//transition.select(".y.axis").call(yAxis);
// New SVG
}
在html中我还为设备兼容性添加了元标记,如下所示:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
即使deveice尺寸很小,也会出现水平滚动条。但我不想横向看到这样的滚动条。我希望图表和地图适合设备宽度。有人可以帮我解决这个问题吗?
答案 0 :(得分:-1)
示例(注意:使用jQuery):
var $graphic = $('#graphic');
function drawGraphic() {
var margin = { top: 10, right: 10, bottom: 30, left: 30 };
var width = $graphic.width() - margin.left - margin.right;
$graphic.empty();
// ... code to create the chart ...
}
d3.csv("data.csv", function(data) { //loading data, may differ
// ... manipulate data here ...
drawGraphic();
window.onresize = drawGraphic;
}
基于D3响应图表的方法:http://blog.apps.npr.org/2014/05/19/responsive-charts.html
我的例子在这里描述:http://bl.ocks.org/michalskop/2fa7d4c0ae029c36ba4e
在此处查看此行动:http://bl.ocks.org/michalskop/raw/2fa7d4c0ae029c36ba4e/
基于Leaflet的响应式地图的演示:http://bl.ocks.org/michalskop/raw/001f6182db52d08f4925/