버튼 클릭 후 JSON 데이터를 D3 막대 그래프로 업데이트하는 데 많은 시간을 할애하고 있습니다.중복 차트로 나타나는 D3 차트 업데이트
버튼을 클릭하여 문제를 해결하는 동안 D3 자바 스크립트가 버튼 클릭당 하나의 차트를 추가하므로 단순히 데이터를 업데이트하는 대신 중복 차트가 표시됩니다.
클릭 이벤트가 트리거 될 때마다 D3 코드에서 append()
을 호출하는 것으로 알고 있지만 클릭당 업데이트 된 데이터가있는 차트가 하나뿐이므로 어떻게이 문제를 해결할 수 있습니까?
console.log('chart.js loaded');
$(document).ready(function() {
var vimeoVideoId = $('p#vimeoVideoId').text();
var api = 'http://localhost:3001/videos/' + vimeoVideoId + '/json';
function initData() {
$('#all-notes').click(function() {
getData();
});
}
function getData() {
$.getJSON(api, draw);
}
function draw(json) {
data = json;
var duration = data.duration;
var timeToSec = function(data) {
notes = [];
// convert min:sec to seconds
for(i=0; i < data.notes.length; i++) {
var min_sec = data.notes[i].timecode;
var tt = min_sec.split(':');
var seconds = tt[0]*60+tt[1]*1;
notes.push(seconds);
}
return notes;
};
noteTimes = timeToSec(data);
console.log(noteTimes);
// Formatters for counts and times (converting numbers to Dates).
var formatCount = d3.format(",.0f"),
formatTime = d3.time.format("%H:%M"),
formatMinutes = function(d) { return formatTime(new Date(2012, 0, 1, 0, d)); };
var margin = {top: 10, right: 20, bottom: 30, left: 20},
width = 550;
height = 285;
var x = d3.scale.linear()
.domain([0, duration])
// .domain([0, d3.max(noteTimes)])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(50))
(noteTimes);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatMinutes);
var svg = d3.select("#chartSet").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 + ")");
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", x(data[0].dx) - 1)
.attr("height", function(d) { return height - y(d.y); });
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(data[0].dx)/2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.y); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
}
initData();
});