Я новичок в d3. js и сейчас учусь рисовать линейную диаграмму с данными JSON из моей базы данных. Проблема в том, что я не могу их показать. Пожалуйста, смотрите скриншот ошибки ниже:
Это мои JSON данные из моего URL
Как Вы можете видеть, что нет проблем с доступом к JSON в моем URL (http://localhost:9090/perHourAvailabilities/2020-04-15
). Но когда я попытался преобразовать их в свой график, я не могу их показать. Я не знаю, связана ли проблема с моим JSON или моим графиком, так как я не могу показать их, и ошибка, которую я получал, это ошибка 404. Я также использую Java Spring для своего проекта.
Это мой код для моей диаграммы:
/* START OF LINE CHART */
$(document).ready(() => {
// set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// parse the date / time
var parseTime = d3.timeParse("%Y");
// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the line
var valueline = d3.line()
.x(function (d) { return x(d.availability_time); })
.y(function (d) { return y(d.total_hour_percentage); });
// define the line
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#lineChart").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 + ")");
function draw(data) {
//console.log(data);
// format the data
data.forEach(function (d) {
d.availability_time = +d.availability_time;
d.total_hour_percentage = +d.total_hour_percentage;
});
// sort time ascending
data.sort(function (a, b) {
return a["availability_time"] - b["availability_time"];
})
// Scale the range of the data
x.domain(d3.extent(data, function (d) {
return d.availability_time;
}));
y.domain([0, d3.max(data, function (d) {
return Math.max(d.total_up_percentage);
})]);
// Add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
}
// Get the data
var perHourResult = "/perHourAvailabilities/" + defaultDate;
console.log(perHourResult);
d3.json(perHourResult)
.then((data) => {
// console.log(data.length);
//console.log(data[0].Date)
// d3.select("#selectButton")
// .selectAll("myOptions")
// .data(data)
// .enter()
// .append("option")
// .text((d) => {
// return d.Date;
// })
// .attr("value", (d) => {
// return d.Date;
// })
//console.log(data[i].Date);
draw(data);
})
.catch((error) => {
console.log(error);
});
});
enter code here
======================= ОБНОВЛЕНИЕ ====== ======================== Обнаружена ошибка в переменной:
кажется, что это то, что вызывает ошибку. Потому что он ожидает, что я верну число, но в моем JSON результате запроса availability_time
является элементом timestamp
. Есть ли способ сделать это строкой или исправить ошибку на <path>
? Также, когда я получаю доступ к (data)
на моей консоли: это показывает это:
============== UPDATE_2 === ===================== Исправлена ошибка на время NaN на консоли. Кажется, что это ошибка:
data.forEach(function (d) {
d.availability_time = +d.availability_time;
d.total_hour_percentage = +d.total_hour_percentage;
});
это должно было быть:
data.forEach(function (d) {
d.availability_time = d.availability_time;
d.total_hour_percentage = +d.total_hour_percentage;
});
, но ошибка на <path>
все еще сохраняется. Кажется, он ожидает число на availability_time