我已经通过从mysql数据库中取两列来创建一个表并转换它json对象它已成功工作但我不是 想知道如何使用这两个柱子绘制条形图。如果有人可以指导我,将会非常有用。 这是我的代码:
{{1}}
答案 0 :(得分:1)
从代码的外观来看,您正在创建一个JavaScript对象,如:
jsonObject = {"sku1": "a string", "sku2": "another string"...
d3.js
虽然非常喜欢使用一系列JavaScript对象:
jsonObject = [
{
sku: "a string",
otherColumn: 3
},
{
sku: "another string",
otherColumn: 4
}
...
其中“sku”是列名,“otherColumn”是值。
因此,要以这种形式获取数据应该像以下一样简单:
JSONArray jsonArray = new JSONArray();
while(rst.next()){
JSONObject jsonObject = new JSONObject();
jsonObject.put("sku", rst.getString(2));
jsonObject.put("otherColumn", rst.getInt(4)); // assuming these are numbers NOT STRINGS or the bar chart would have nothing to draw
jsonArray.put(jsonObject);
}
// rest of java code here, close out connections, etc...
%>
<script>
// switch over to JavaScript and d3
// get java variable into JavaScript
var javaScriptData = "<%out.print(jsonArray.toString());%>";
// bar chart code goes here
....
要创建条形图,请查看this sample code:
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
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(10, "%");
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 + ")");
x.domain(javaScriptData.map(function(d) { return d.sku; }));
y.domain([0, d3.max(javaScriptData, function(d) { return d.otherColumn; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("otherColumn");
svg.selectAll(".bar")
.data(javaScriptData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.sku); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.otherColumn); })
.attr("height", function(d) { return height - y(d.otherColumn); });