【发布时间】:2014-05-17 02:19:26
【问题描述】:
我需要在图表中绘制销售数据,并选择了 nvd3.js 来执行此操作。这是我图表的代码 sn-p: 变量图表;
nv.addGraph(function () {
chart = nv.models.lineChart()
.options({
margin: {
left: 100,
bottom: 100
},
x: function (d, i) {
return i
},
showXAxis: true,
showYAxis: true,
transitionDuration: 250
});
chart.xAxis.axisLabel("Date")
.tickFormat(function (d) {
return d3.time.format('%B %d, %Y')(new Date(d));
});
chart.yAxis.axisLabel("Dollars $")
.tickFormat(d3.format(',.2f'));
d3.select('#chart1 svg')
.datum(salesdata())
.call(chart);
//TODO: Figure out a good way to do this automatically
nv.utils.windowResize(chart.update);
//nv.utils.windowResize(function() { d3.select('#chart1 svg').call(chart) });
chart.dispatch.on('stateChange', function (e) {
nv.log('New State:', JSON.stringify(e));
});
return chart;
});
function salesdata() {
var pin = [],
product = [],
service = [],
fee = [],
repair = [],
total = [],
sales = {
"February 20, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 160.00,
"pins": 0,
"total": 160.00
},
"January 22, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 12.00,
"total": 12.00
},
"January 07, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 2496.95,
"total": 2496.95
},
"January 08, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 3124.95,
"total": 3124.95
},
"January 11, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 961.10,
"total": 961.10
},
"January 09, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 2094.50,
"total": 2094.50
},
"February 18, 2014": {
"repairs": 410.00,
"services": 360.00,
"products": 0,
"fees": 270.00,
"pins": 69.95,
"total": 1109.95
},
"January 13, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 1229.05,
"total": 1229.05
},
"January 10, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 3544.45,
"total": 3544.45
},
"January 06, 2014": {
"repairs": 0,
"services": 0,
"products": 0,
"fees": 0,
"pins": 3825.55,
"total": 3825.55
}
};
for (i in sales) {
pin.push({
x: i,
y: sales[i].pins
});
product.push({
x: i,
y: sales[i].products
});
service.push({
x: i,
y: sales[i].services
});
fee.push({
x: i,
y: sales[i].fees
});
total.push({
x: i,
y: sales[i].total
});
repair.push({
x: i,
y: sales[i].repairs
});
};
return [{
values: total,
key: "Total",
color: "#abcdef"
}, {
values: pin,
key: "PINs",
color: "#ff7f0e"
}, {
values: product,
key: "Products",
color: "#ccdd33"
}, {
values: fee,
key: "Fees",
color: "#2222ff"
}, {
values: service,
key: "Services",
color: "#667711"
}, {
values: repair,
key: "Repairs",
color: "#eeccff"
}];
}
我选择在一个简单的svg 元素中制作图表,如下所示:
<div id="chart1" >
<svg style="height: 500px;"></svg>
</div>
不幸的是,x 轴上的日期似乎有问题,图表看起来像 like this
我尝试了许多通过谷歌搜索找到的解决方案(例如 this),尝试了 Date 函数和一些格式化程序,但似乎无法找出导致日期从错误日期开始的原因。
有人知道这是什么原因吗?
谢谢
【问题讨论】:
标签: javascript svg d3.js charts nvd3.js