Я пытаюсь отфильтровать данные до одного значения на основе ввода. Если пользователь вводит значение, я хочу, чтобы он мог отображать только это значение на графике. Однако это не работает. Я считаю, что код находится во всех нужных местах, просто логики там нет.
Если я удалю функциональность, которая пытается это сделать, все будет в порядке — это означает, что если я нажму на A, будут возвращены только данные с типом A, и то же самое с B. Но это не работает, когда я реализую свой код, который пытается настроить до одного значения.
Вопрос:
Как я могу отфильтровать одно значение по оси x на основе пользовательского ввода, но при этом сохранить функциональность, которая позволяет пользователю переключаться между типами данных.
$(document).ready(function() {
$("#input").attr("value", 0);
});
const margin = {
top: 10,
right: 30,
bottom: 70,
left: 65
},
width = 520,
height = 480;
function SVGmaker(target) {
const svg = d3.selectAll(target)
.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 + ")")
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", height)
.attr("width", width)
.attr("fill", "white")
return svg;
}
const svgOne = SVGmaker("#svg");
const data = [{
x: "1",
y: "5",
type: "A"
},
{
x: "2",
y: "4",
type: "B"
},
{
x: "3",
y: "3",
type: "B"
},
{
x: "4",
y: "2",
type: "A"
},
{
x: "5",
y: "1",
type: "A"
}
]
let x = d3.scaleLinear()
.domain([1, 5])
.range([0, width]);
// DC SVG Settings
const xAxis = d3.axisBottom(x);
svgOne.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
const yAxis = d3.scaleLinear()
.domain([0, 6])
.range([height, 0])
svgOne.append("g")
.call(d3.axisLeft(yAxis));
const colors = d3.scaleOrdinal()
.domain(["A", "B"])
.range(["red", "blue"]);
function updateData(data, type, theSVG, xAxis, yAxis, colors, value) {
// Filters through the data
const changeData = data.filter(function(d) {
if (type === "A") {
return d.type === "A"
} else if (type === "B") {
return d.type === "B"
} else {
return true;
}
});
var min = d3.min(data, function(d) {
return d.x;
});
const gra = theSVG
.selectAll("circle")
.data(changeData);
gra.enter()
.append("circle")
.filter(function(d) {
if (value <= min) {
return d.x
} else {
return d.x >= value && d.x <= value
}
})
.attr("cx", function(d) {
return xAxis(d.x);
})
.attr("cy", function(d) {
return yAxis(d.y);
})
.style("fill", function(d) {
return colors(d.type)
})
.merge(gra)
.attr("r", 11)
.filter(function(d) {
if (value <= min) {
return d.x
} else {
return d.x >= value && d.x <= value
}
})
.attr("cx", function(d) {
return xAxis(d.x);
})
.attr("cy", function(d) {
return yAxis(d.y);
})
.style("fill", function(d) {
return colors(d.type)
})
gra.exit()
.remove();
}
updateData(data, "", svgOne, x, yAxis, colors, 0);
let value;
function getMessage() {
value = document.getElementById("#input").value;
}
d3.select("#a")
.on("click", function() {
updateData(data, "A", svgOne, x, yAxis, colors, value);
});
d3.select("#b")
.on("click", function() {
updateData(data, "B", svgOne, x, yAxis, colors, value);
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<div id = "svg"></div>
<button id = "a">a</button>
<button id = "b">b</button>
<input type = "number" id = "input" value=0>
<button id = "submit">submit</button>
<script type = "text/javascript" src = "scripts.js"></script>
Я сделал что-то подобное. Это полезно, но мне точно не помогает
Я немного догадывался, что вы хотите сделать, но на самом деле проблема заключалась в том, что вы никогда не устанавливали переменную «значение», и поэтому вы всегда передавали значение undefined.
Когда вы вызываете getElementById, не включайте #
.
Как правило, если вы не создаете тег/элемент с помощью d3 или js, я бы лично прикрепил прослушиватель кликов с атрибутом onclick
прямо внутри html вместо d3.on.
$(document).ready(function() {
$("#input").attr("value", 0);
});
const margin = {
top: 10,
right: 30,
bottom: 70,
left: 65
},
width = 520,
height = 480;
function SVGmaker(target) {
const svg = d3.selectAll(target)
.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 + ")")
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", height)
.attr("width", width)
.attr("fill", "white")
return svg;
}
const svgOne = SVGmaker("#svg");
const data = [{
x: "1",
y: "5",
type: "A"
},
{
x: "2",
y: "4",
type: "B"
},
{
x: "3",
y: "3",
type: "B"
},
{
x: "4",
y: "2",
type: "A"
},
{
x: "5",
y: "1",
type: "A"
}
]
let x = d3.scaleLinear()
.domain([1, 5])
.range([0, width]);
// DC SVG Settings
const xAxis = d3.axisBottom(x);
svgOne.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
const yAxis = d3.scaleLinear()
.domain([0, 6])
.range([height, 0])
svgOne.append("g")
.call(d3.axisLeft(yAxis));
const colors = d3.scaleOrdinal()
.domain(["A", "B"])
.range(["red", "blue"]);
function updateData(data, type, theSVG, xAxis, yAxis, colors, value) {
// Filters through the data
var min = d3.min(data, function(d) {
return d.x;
});
const changeData = data
.filter(function(d) {
if (value >= min) {
return d.x == value;
} else {
return true;
}
})
.filter(function(d) {
if (type === "A") {
return d.type === "A"
} else if (type === "B") {
return d.type === "B"
} else {
return true;
}
});
const gra = theSVG
.selectAll("circle")
.data(changeData);
gra.enter()
.append("circle")
.attr("r", 11)
.style("fill", function(d) {
return colors(d.type)
})
.merge(gra)
.attr("cx", function(d) {
return xAxis(d.x);
})
.attr("cy", function(d) {
return yAxis(d.y);
})
.style("fill", function(d) {
return colors(d.type)
})
gra.exit()
.remove();
}
updateData(data, "", svgOne, x, yAxis, colors, 0);
d3.select("#submit")
.on("click", function() {
var value = document.getElementById("input").value;
updateData(data, "", svgOne, x, yAxis, colors, value);
});
d3.select("#a")
.on("click", function() {
updateData(data, "A", svgOne, x, yAxis, colors, 0);
});
d3.select("#b")
.on("click", function() {
updateData(data, "B", svgOne, x, yAxis, colors, 0);
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<div id = "svg"></div>
<button id = "a">a</button>
<button id = "b">b</button>
<input type = "number" id = "input" value=0>
<button id = "submit">submit</button>
<script type = "text/javascript" src = "scripts.js"></script>
проверьте этот stackoverflow.com/questions/56291849/…