【发布时间】:2020-04-28 06:52:10
【问题描述】:
我有一个使用 d3 v5 创建的条形图,它需要有一条直线作为“限制”,具体取决于特定的 y 值。
这是我目前拥有的图表和应该创建的线(添加在油漆上)
这是创建图表的代码
(async ()=> {
const response = await fetch('https://api);
const myJson = await response.json();
//need myJson.DailyDelvs to be the y value of the line
// set the dimensions and margins of the graph
var margin = {top: 30, right: 30, bottom: 70, left: 60},
width = 400 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom
tip = d3.tip()
.attr('class', 'd3-tip')
.html(function(d) { return "DAY: "+d.DIA+"<br/>PO: "+d.PO_ID })
// append the svg object to the body of the page
var svg = d3.select("#dailyDeliveryVolume")
.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 + ")")
.call(tip)
var datos
// get the data
d3.json("https://api2").then(function(data) {
datos = data
d3.select("#dailyDeliveryVolume_spinner").remove();
var x = d3.scaleBand()
.range([ 0, width ])
.domain([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31])
.padding(0.05);
var xAxis = d3.axisBottom(x)
.tickValues(x.domain().filter(function(d,i){ return !(i%2)}));
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
var y = d3.scaleLinear()
.domain([0, d3.max(data.STD, function(d) { return +d.PO_ID })])
.range([ height, 0]);
svg.append("g")
.call(d3.axisLeft(y))
// Bars
svg.selectAll("mybar")
.data(data.STD)
.enter()
.append("rect")
.attr("x", function(d) { return x(d.DIA); })
.attr("y", function(d) { return y(d.PO_ID); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.PO_ID); })
.attr("fill", "#69b3a2")
.attr("border-color", "black")
.on("mouseover", tip.show)
.on("mouseleave", tip.hide )
})
})()
为了创建该行,我尝试了以下代码,就在我追加了条之后,这导致了错误
var linea = drawLine(svg, x, y, data.STD);
var drawLine = function(svg, x, y, data) {
var lineFunc = d3.line()
.x(function(obj) {
return x(obj.DIA);
})
.y(function(obj) {
return y(obj.PO_ID);
});
var linea = svg.append("linea") //SVG Paths represent the outline of a shape that can be stroked, filled, used as a clipping path, or any combination of all three. We can draw rectangles, circles, ellipses, polylines, polygons, straight lines, and curves through path
.attr("d", lineFunc(data))
.attr("stroke", '#87CEEB')
.attr("stroke-width", 3)
.attr("fill", "black");
return linea;
};
dailyDeliveryVolume.js:64 Uncaught (in promise) TypeError: drawLine is not a function at dailyDeliveryVolume.js:64
我还尝试使用固定属性 x1、x2、y1 和 y2 直接向 svg 附加一条线,但似乎它是基于整个容器完成的,无法适应 x 和 y 轴值。
目标是 myJson.DailyDelvs 是 y 值(基于 y 比例值),然后直接穿过所有宽度。
【问题讨论】:
标签: javascript d3.js svg charts line