2017-02-12 70 views
0

我試圖設置一個簡單的條形圖使用D3版本4.x.x但是,我相信我正在做的一切正確,但似乎無法得到rects顯示。我附上了一個codepen來看看這個。D3 Rect元素不顯示

非常感謝您提前解決這個問題,因爲我是D3的新手。 http://codepen.io/PizzaPokerGuy/pen/XpoJxG?editors=0111

enter code here//Width of svg, will be used again down the road 
const width = 1000; 
//Height of svg, will be used again down the road 
const height = 800; 
//Padding so things have room to be displayed within svg 
const padding = 60; 
//Create our SVG container 
var svg = d3.select("body") 
.append('svg') 
.attr("width", width) 
.attr("height", height); 

//JSON Enter data 
var data =  d3.json('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/mast er/GDP-data.json', 
    (error, data) => { 
    var chartData = data.data; 
    //Stores barWidth variable, math.ciel rounds up, used to set an equal width for each rect 
    var barWidth = Math.ceil((width - padding)/chartData.length); 
    //Define xScale 
    const xScale = d3.scaleLinear() 
    .domain([0, d3.max(chartData, (d) => d[0])]) 
    .range([padding, width - padding]); 
    //Define yScale 
const yScale = d3.scaleLinear() 
    .domain([0, d3.max(chartData, (d) => d[1])]) 
    .range([height - padding, padding]); 

//Selects SVG elements and selects all rect elements within it 
svg.selectAll("rect") 
    //Adds data to use later 
    .data(chartData) 
    //Allows us to add items to the dom if data is larger than ammoutn of rect elements selected 
    .enter() 
    //Adds rect element 
    .append("rect") 
    //Adds x attribute to x based off of d(chartData), need to create a date as a string is not enough 
    .attr("x", (d) => xScale(new Date(d[0]))) 
    //Sets y attribute of rectangle 
    .attr("y", (d) => yScale(d[1])) 
    //Sets height, we minus the value from height to invert the bars 
    .attr("height", (d) => height - yScale(d[1])) 
    //sets width of rect elements 
    .attr("width", barWidth) 
    //fill in color of rects 
    .attr("fill", "black"); 

});

回答

1

您正在使用日期X軸,所以你就可以更好地使用時間尺度,而不是scaleLinear

const xScale = d3.scaleTime() 
    .domain(d3.extent(chartData, function(d) { return new Date(d[0]); })) 
    .range([padding, width - padding]); 

Codepen:http://codepen.io/anon/pen/egbGaJ?editors=0111

+0

非常感謝。這解決了我的問題。這很有道理。 – user2872518

0

你的X值是表示日期的字符串,但你並沒有試圖像這樣對待他們。您當前的scale代碼期望它們是數字。所以你需要決定將它們創建爲字符串或日期。例如,將它們強制轉換爲日期將如下所示;

// a time parser 
var tF = d3.timeParse("%Y-%m-%d"); 
// convert to dates 
chartData.forEach(function(d){ 
    d[0] = tF(d[0]) 
}); 

... 

//Define xScale as a time scale 
const xScale = d3.scaleTime() 
    .domain([0, d3.max(chartData, (d) => d[0])]) 
... 

更新codepen