我是编程新手,也是 D3 新手,我正在使用“D3 入门”一书以及我可以在互联网上找到的所有示例来学习它。
要开始练习,我正在尝试创建一个柱形图,但我的 x-label 遇到了两个问题:
- 我的 x 轴下方显示的标签与列不一致。准确地说,我在标签开始显示之前显示了数字。
- 我想知道如何旋转标签。当我尝试旋转属性时,所有 x 轴都在旋转,我只想旋转标签。我发现了一些与此相关的问题,但还没有完全理解答案。
我的数据是这样格式化的:
{"Low_Income_Household_Internet_access":
[{"Country":"Chile","Value":9.69},
{"Country":"New Zealand","Value":47.8},
{"Country":"Greece","Value":25.39},
{"Country":"Italy","Value":33.26},
{"Country":"Israel","Value":40.31},
{"Country":"Portugal","Value":22.72},
{"Country":"United Kingdom","Value":56},...
],
"High_Income_Household_Internet_access":
[{"Country":"Chile","Value":59.78701735},
{"Country":"New Zealand","Value":78.3},
{"Country":"Greece","Value":81.14},
{"Country":"Italy","Value":84.44},
{"Country":"Israel","Value":86.59},
{"Country":"Portugal","Value":89.73},
{"Country":"United Kingdom","Value":90},...
]}
我的代码如下:
function draw(data) {
"use strict";
var w = 600;
var h = 300;
var barPadding = 3;
var margin=20;
var format = d3.format(",.0f");
var x = d3.scale.ordinal().rangeBands([0, w-margin], .1),
y = d3.scale.linear().range([h-margin, margin]);
var xAxis = d3.svg.axis().scale(x).orient("top").tickSize(0),
yAxis = d3.svg.axis().scale(y).orient("left").tickSize(-w);
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + margin + ",0)");
// Set the scale domain.
x.domain(d3.range(data.Low_Income_Household_Internet_access.length));
y.domain([0, d3.max(data.Low_Income_Household_Internet_access,function(d) { return d.Value; }) ]);
var bar = svg.selectAll("g.bar")
.data(data.Low_Income_Household_Internet_access)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.Country)+ "," + y(d.Value) + " ) "; });
bar.append("rect")
.attr("width", x.rangeBand())
.attr("height", function(d) { return h-margin- y(d.Value); })
.on("mouseover",function(d) {
d3.select(this)
.style("fill","red")
})
.on("mouseout",function(d) {
d3.select(this)
.style("fill","grey")
})
.append("svg:title")
.text(function(d) { return "" + d.Country + ": " + d.Value + " %"; });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, 295)")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);}