【发布时间】:2017-05-01 20:50:06
【问题描述】:
我的数据如下:
var chartData = [[9.402974983096687, "Asian"], [10.762177012177013, "Black"], [12.213470319634704, "Chinese"], [11.211221431247658, "Hispanic"], [9.18421052631579, "American Indian"], [12.36144578313253, "Japanese"], [14.659334126040427, "Other"], [7.5, "Portuguese"], [10.636304446904095, "White"]];
我正在尝试将其转换为格式:
[
{
"Ethinicity": "Asian",
"Facebook_usage": 9.40
},
{
"Ethinicity" : "Black",
"Freq": 12.213470319634704
},
{
"Ethinicity":"Chinese"
"Freq": 12.213470319634704
},
----]
然后,以此为基础制作条形图。尝试使用地图功能如下:
chartData.map(function(e, i) {
facebook_usage.push(e[0]);
ethinicity.push(e[1]);
}
var chartData = create_JSON(facebook_usage,ethinicity) {
--not sure how to frame this function }
这是绘制条形图的其余代码:
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// set the ranges
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);
// define the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
// add the SVG element
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 + ")");
// load the data
chartData.forEach(function(d) {
d.ethinicity = d.ethinicity;
d.facebook_usage = d.facebook_usage;
});
// scale the range of the data
x.domain(data.map(function(d) { return d.ethinicity; }));
y.domain([0, d3.max(data, function(d) { return d.facebook_usage; })]);
// add axis
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", 5)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
// Add bar chart
svg.selectAll("bar")
.data(chartData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.ethinicity); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.facebook_usage); })
.attr("height", function(d) { return height - y(d.facebook_usage); });
仍在尝试找到解决 d3.js 的方法。下面是fiddle
【问题讨论】:
标签: javascript json d3.js bar-chart