在条形图中,我将左y
轴值设为string
格式,如何将这些值设置为xAxis
- 刻度?
这是我的代码:请在评论中查看详细信息
window.onload = function(){
var margin = { left:30, top:30, right:30, bottom:30 },
width = 550 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom,
totalWidth = width + margin.left + margin.right,
totalHeight = height + margin.top + margin.bottom;
var data = [5,20,80,120,35,90,340, 145, 601, 11, 67, 810 ];
var yData = [2012,2013,2014,2015,2016];
//how to set aData to yAxis?
var aData = ['0','$50M','$1B','$1.5B','$2B', '$2.5B','$3B'];
var y = d3.scale.linear().range([height, 0]);
var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);
x.domain(yData.map(function(d) { return d; }));
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).tickFormat(function(d){
return d; //i required to set from aData
}).orient("left").ticks(5);
var svg = d3.select('#container').append('svg').attr({width:totalWidth,height:totalHeight});
var graphMargin = "translate(" + margin.left + ',' + margin.top + ')';
var playBoard = svg.append('g').attr("transform", graphMargin);
playBoard.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height+1) + ")")
.call(xAxis);
playBoard.append("g")
.attr("class", "y axis")
.call(yAxis);
}
提前致谢。
答案 0 :(得分:0)
请检查以下代码,我用它来渲染条形图。它绘制了沿x轴的时间戳和沿y轴的值。
function RenderLineChart(data) {
// Set the dimensions of the canvas / graph
var margin = { top: 30, right: 20, bottom: 30, left: 50 },
width = 960 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
// Parse the date / time
var parseTime = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function (d) { return x(d.Timestamp); })
.y(function (d) { return y(d.Value); });
// Adds the svg canvas
var svg = d3.select("#d3Graph")
.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 + ")");
data.forEach(function (d) {
d.Timestamp = parseTime(d.Timestamp);
d.Value = +d.Value;
});
// Scale the range of the data
x.domain(d3.extent(data, function (d) { return d.Timestamp; }));
y.domain([0, d3.max(data, function (d) { return d.Value; })]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
}
以下代码定义了轴。
// Define the line
var valueline = d3.svg.line()
.x(function (d) { return x(d.Timestamp); })
.y(function (d) { return y(d.Value); });