2017-02-12 1 views
0

D3 버전 4.x.x를 사용하여 간단한 막 대형 차트를 설정하려고합니다. 그러나 모든 것을 올바르게하고 있지만 rect를 표시 할 수없는 것 같습니다. 이것을 보려고 코덱을 붙였습니다.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 사용하는 것이 좋습니다 수 있습니다 : 당신이 값이 날짜를 나타내는 문자열입니다 X http://codepen.io/anon/pen/egbGaJ?editors=0111

+0

대단히 감사합니다. 이것은 내 문제를 해결했습니다. 그것은 많은 의미가 있습니다. – user2872518

0

을하지만, 그 (것)들을 그런 것과 같이 대우하는 시도를 만들지 않았다. 현재 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 업데이트 됨.

관련 문제