gpt4 book ai didi

javascript - 将线和点与折线图中的 x 轴值对齐

转载 作者:行者123 更新时间:2023-12-04 15:00:14 27 4
gpt4 key购买 nike

我使用 d3.v4.min.js 框架创建了一个简单的折线图视觉对象。

视觉效果如下:

enter image description here

如您所见,我的问题是线及其点与 x 轴的对齐。
您可以在下面找到实现的代码。我希望两条线都从 Germany 开始,而不是从 y 轴开始。我猜测由于 x 轴是分类的而不是数字的,javascript 无法区分起点,所以它从 y 轴绘制线条。

data=[{dValues: "Germany", m1Values: 3323936.920000017, m2Values: 1469934.4999999946},
{dValues: "Japan", m1Values: 11847615.030000022, m2Values: 4860290.499999991},
{dValues: "Nordic", m1Values: 10382965.910000034, m2Values: 4289934.389999997},
{dValues: "Spain", m1Values: 3449601.7199999965, m2Values: 1594701.149999997},
{dValues: "UK", m1Values: 28157182.22999989, m2Values: 12590207.999999987},
{dValues: "USA", m1Values: 47691372.99999974, m2Values: 18448120.5719999}]

// helper Function to round the displayed numbers
var roundNumber = function roundNumber(num, noPrecision){
//check if the string passed is number or contains formatting like 13%
if (/^[0-9.]+$/.test(num)) {
num = !noPrecision ? parseFloat(num).toFixed(2) : Math.round(num);
if (num >= 1000 && num < 1000000) {
num = !noPrecision ? parseFloat(num / 1000).toFixed(2) : Math.round(num / 1000);
if (/\.00$/.test(num)) {
num = num.replace(/\.00$/, ''); // Remove .00
}
num += 'K'; // Add the abbreviation
} else if (num >= 1000000 && num < 1000000000) {
num = !noPrecision ? parseFloat(num / 1000000).toFixed(2) : Math.round(num / 1000000);
if (/\.00$/.test(num)) {
num = num.replace(/\.00$/, ''); // Remove .00
}
num += 'M'; // Add the abbreviation
} else if (num >= 1000000000) {
num = !noPrecision ? parseFloat(num / 1000000000).toFixed(2) : Math.round(num / 1000000000);
if (/\.00$/.test(num)) {
num = num.replace(/\.00$/, ''); // Remove .00
}
num += 'T'; // Add the abbreviation
}
}
return num;
};

// Step 1: set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 50, left: 60 }; //adjust left margin to show how y-axis +20 in bottom and left for X,Y axis titles
var width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

// Step 2: set the ranges for x, y axis
// var n = 21;

var xScale = d3.scaleBand().range([0, width]);
var yScale = d3.scaleLinear().range([height, 0]);

//Line generator 1
var valueline1 = d3.line()
.x(function(d) { return xScale(d.dValues); })
.y(function(d) { return yScale(d.m1Values); })
.defined(function(d) {
if (isNaN(d.m1Values)) {
d.m1Values = 0;
}
return d.m1Values !== 0;
});
//.curve(d3.curveNatural);

//Line generator 2
var valueline2 = d3.line()
.x(function(d) { return xScale(d.dValues); })
.y(function(d) { return yScale(d.m2Values); })
.defined(function(d) {
if (isNaN(d.m2Values)) {
d.m2Values = 0;
}
return d.m2Values !== 0;
});
//.curve(d3.curveNatural);
//-----------------------------------------------------------------------------
// Build the svg chart
var svg = d3.select("body").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 + ")");

data.forEach(function(d) {
d.dValues = d.dValues;
d.m1Values = +d.m1Values;
d.m2Values = +d.m2Values;
});

//xScale.domain(d3.extent(data, function(d) { return d.dValues; }));
xScale.domain(data.map(function(d) { return d.dValues; }));
//xScale.domain([data[0].dValues, data[data.length-1].dValues]);
//yScale.domain([d3.min(data, function(d) { return Math.min(d.m1Values, d.m2Values); }), d3.max(data, function(d) { return Math.max(d.m1Values, d.m2Values); }) ]);
yScale.domain([0, d3.max(data, function(d) { return Math.max(d.m1Values, d.m2Values); })]);

var lines = svg.attr('transform', function(d) { return 'translate(' + margin.left + ', ' + margin.top + ')'; });
//var lines = svg.attr("transform", function(d) { return "translate(" + (xScale(d.dValues)) + ",0)"; });

//add valueline 1 path //append to lines or svg
lines.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline1);

//add valueline 2 path
lines.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "red")
.attr("d", valueline2);

// Define the div for the tooltip
/* var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.html("tooltip")
.style("position", "absolute")
.style("opacity", 0); */
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([-25, 0])
.html(function(d) { return d.dValues + ": " + roundNumber(d.m1Values);});
svg.call(tool_tip);

svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot1")
.attr("cx", function(d){ return xScale(d.dValues); })
.attr("cy", function(d){return yScale(d.m1Values); })
.attr("r", 5)
.on('mouseover', tool_tip.show)
.on('mouseout', tool_tip.hide);

svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot2")
.attr("cx", function(d){ return xScale(d.dValues) })
.attr("cy", function(d){return yScale(d.m2Values)})
.attr("r", 5);

svg.append("text")
.attr("transform", "translate(" + (xScale(data[data.length - 1].dValues) + 5) + "," + yScale(data[data.length - 1].m1Values) + ")")
.attr("dy", ".35em")
.attr("text-anchor", "start")
.style("fill", "black")
.text("Sum(Sales)");

svg.append("text")
.attr("transform", "translate(" + (xScale(data[data.length - 1].dValues) + 5) + "," + yScale(data[data.length - 1].m2Values)+ ")")
.attr("dy", ".35em")
.attr("text-anchor", "start")
.style("fill", "black")
.text("Sum(Margin)");

svg.append("g")
.classed("labels-group", true)
.selectAll("text")
.data(data)
.enter()
.append("text")
.classed("label", true)
.attr("x", function(d) { return xScale(d.dValues) - 20 + "px"; })
.attr("y", function(d) { return yScale(d.m1Values) - 10 + "px"; })
.text(function(d) { return roundNumber(d.m1Values); });

svg.append("g")
.classed("labels-group", true)
.selectAll("text")
.data(data)
.enter()
.append("text")
.classed("label", true)
.attr("x", function(d) { return xScale(d.dValues) - 20 + "px"; })
.attr("y", function(d) { return yScale(d.m2Values) - 10 + "px"; })
.text(function(d) { return roundNumber(d.m2Values); });

//Add x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));

// Add the y Axis
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale).tickFormat(d3.format(".2s")));

var legend = svg.append("g")
.attr("font-family", "Helvetica")
.attr("font-size", 10)
.attr("text-anchor", "end")
.selectAll("g")
.data(["Sum(Sales)", "Sum(Margin)"])
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

var color = d3.scaleOrdinal().range(["#ffab00", "red"]);
legend.append("rect")
.attr("x", width - 19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", color);

legend.append("text")
.attr("x", width - 24)
.attr("y", 9.5)
.attr("dy", "0.32em")
.text(function(d) { return d; });
.line {
fill: none;
stroke: #ffab00;
stroke-width: 3;
}

/* Style the dots by assigning a fill and stroke */
.dot1 {
fill: #ffab00;
stroke: #fff;
}
.dot2 {
fill: red;
stroke: #fff;
}

.d3-tip {
line-height: 1;
padding: 6px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 4px;
font-size: 12px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}

/* Style northward tooltips specifically */
.d3-tip.n:after {
margin: -2px 0 0 0;
top: 100%;
left: 0;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.min.js" integrity="sha512-a+/SD0dbGeXTN4AA5F1dDZqsPvXKKyS1bvU2z5ElpKNJ4xQlOMUs/1+suA+j+kj5nAAya+VmT5HUKZmazluxVQ==" crossorigin="anonymous"></script>

提前感谢任何建议。

最佳答案

将线/点/标签的 xScale 替换为 correctXScale:

const correctXScale = d => xScale(d.dValues) + width / data.length / 2;

xScale 不起作用,因为您使用的是带刻度

data=[{dValues: "Germany", m1Values: 3323936.920000017, m2Values: 1469934.4999999946},
{dValues: "Japan", m1Values: 11847615.030000022, m2Values: 4860290.499999991},
{dValues: "Nordic", m1Values: 10382965.910000034, m2Values: 4289934.389999997},
{dValues: "Spain", m1Values: 3449601.7199999965, m2Values: 1594701.149999997},
{dValues: "UK", m1Values: 28157182.22999989, m2Values: 12590207.999999987},
{dValues: "USA", m1Values: 47691372.99999974, m2Values: 18448120.5719999}]

// helper Function to round the displayed numbers
var roundNumber = function roundNumber(num, noPrecision){
//check if the string passed is number or contains formatting like 13%
if (/^[0-9.]+$/.test(num)) {
num = !noPrecision ? parseFloat(num).toFixed(2) : Math.round(num);
if (num >= 1000 && num < 1000000) {
num = !noPrecision ? parseFloat(num / 1000).toFixed(2) : Math.round(num / 1000);
if (/\.00$/.test(num)) {
num = num.replace(/\.00$/, ''); // Remove .00
}
num += 'K'; // Add the abbreviation
} else if (num >= 1000000 && num < 1000000000) {
num = !noPrecision ? parseFloat(num / 1000000).toFixed(2) : Math.round(num / 1000000);
if (/\.00$/.test(num)) {
num = num.replace(/\.00$/, ''); // Remove .00
}
num += 'M'; // Add the abbreviation
} else if (num >= 1000000000) {
num = !noPrecision ? parseFloat(num / 1000000000).toFixed(2) : Math.round(num / 1000000000);
if (/\.00$/.test(num)) {
num = num.replace(/\.00$/, ''); // Remove .00
}
num += 'T'; // Add the abbreviation
}
}
return num;
};

// Step 1: set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 50, left: 60 }; //adjust left margin to show how y-axis +20 in bottom and left for X,Y axis titles
var width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

// Step 2: set the ranges for x, y axis
// var n = 21;

var xScale = d3.scaleBand().range([0, width]);
var yScale = d3.scaleLinear().range([height, 0]);

const correctXScale = d => {
return xScale(d.dValues) + width / data.length / 2;
}

//Line generator 1
var valueline1 = d3.line()
.x(function(d) { return correctXScale(d); })
.y(function(d) { return yScale(d.m1Values); })
.defined(function(d) {
if (isNaN(d.m1Values)) {
d.m1Values = 0;
}
return d.m1Values !== 0;
});
//.curve(d3.curveNatural);

//Line generator 2
var valueline2 = d3.line()
.x(function(d) { return correctXScale(d); })
.y(function(d) { return yScale(d.m2Values); })
.defined(function(d) {
if (isNaN(d.m2Values)) {
d.m2Values = 0;
}
return d.m2Values !== 0;
});
//.curve(d3.curveNatural);
//-----------------------------------------------------------------------------
// Build the svg chart
var svg = d3.select("body").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 + ")");

data.forEach(function(d) {
d.dValues = d.dValues;
d.m1Values = +d.m1Values;
d.m2Values = +d.m2Values;
});

//xScale.domain(d3.extent(data, function(d) { return d.dValues; }));
xScale.domain(data.map(function(d) { return d.dValues; }));
//xScale.domain([data[0].dValues, data[data.length-1].dValues]);
//yScale.domain([d3.min(data, function(d) { return Math.min(d.m1Values, d.m2Values); }), d3.max(data, function(d) { return Math.max(d.m1Values, d.m2Values); }) ]);
yScale.domain([0, d3.max(data, function(d) { return Math.max(d.m1Values, d.m2Values); })]);

var lines = svg.attr('transform', function(d) { return 'translate(' + margin.left + ', ' + margin.top + ')'; });
//var lines = svg.attr("transform", function(d) { return "translate(" + (xScale(d.dValues)) + ",0)"; });

//add valueline 1 path //append to lines or svg
lines.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline1);

//add valueline 2 path
lines.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "red")
.attr("d", valueline2);

// Define the div for the tooltip
/* var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.html("tooltip")
.style("position", "absolute")
.style("opacity", 0); */
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([-25, 0])
.html(function(d) { return d.dValues + ": " + roundNumber(d.m1Values);});
svg.call(tool_tip);

svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot1")
.attr("cx", function(d){ return correctXScale(d); })
.attr("cy", function(d){return yScale(d.m1Values); })
.attr("r", 5)
.on('mouseover', tool_tip.show)
.on('mouseout', tool_tip.hide);

svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot2")
.attr("cx", function(d){ return correctXScale(d) })
.attr("cy", function(d){return yScale(d.m2Values)})
.attr("r", 5);

svg.append("text")
.attr("transform", "translate(" + (xScale(data[data.length - 1].dValues) + 5) + "," + yScale(data[data.length - 1].m1Values) + ")")
.attr("dy", ".35em")
.attr("text-anchor", "start")
.style("fill", "black")
.text("Sum(Sales)");

svg.append("text")
.attr("transform", "translate(" + (xScale(data[data.length - 1].dValues) + 5) + "," + yScale(data[data.length - 1].m2Values)+ ")")
.attr("dy", ".35em")
.attr("text-anchor", "start")
.style("fill", "black")
.text("Sum(Margin)");

svg.append("g")
.classed("labels-group", true)
.selectAll("text")
.data(data)
.enter()
.append("text")
.classed("label", true)
.attr("x", function(d) { return correctXScale(d) - 20 + "px"; })
.attr("y", function(d) { return yScale(d.m1Values) - 10 + "px"; })
.text(function(d) { return roundNumber(d.m1Values); });

svg.append("g")
.classed("labels-group", true)
.selectAll("text")
.data(data)
.enter()
.append("text")
.classed("label", true)
.attr("x", function(d) { return correctXScale(d) - 20 + "px"; })
.attr("y", function(d) { return yScale(d.m2Values) - 10 + "px"; })
.text(function(d) { return roundNumber(d.m2Values); });

//Add x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));

// Add the y Axis
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale).tickFormat(d3.format(".2s")));

var legend = svg.append("g")
.attr("font-family", "Helvetica")
.attr("font-size", 10)
.attr("text-anchor", "end")
.selectAll("g")
.data(["Sum(Sales)", "Sum(Margin)"])
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

var color = d3.scaleOrdinal().range(["#ffab00", "red"]);
legend.append("rect")
.attr("x", width - 19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", color);

legend.append("text")
.attr("x", width - 24)
.attr("y", 9.5)
.attr("dy", "0.32em")
.text(function(d) { return d; });
.line {
fill: none;
stroke: #ffab00;
stroke-width: 3;
}

/* Style the dots by assigning a fill and stroke */
.dot1 {
fill: #ffab00;
stroke: #fff;
}
.dot2 {
fill: red;
stroke: #fff;
}

.d3-tip {
line-height: 1;
padding: 6px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 4px;
font-size: 12px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}

/* Style northward tooltips specifically */
.d3-tip.n:after {
margin: -2px 0 0 0;
top: 100%;
left: 0;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.min.js" integrity="sha512-a+/SD0dbGeXTN4AA5F1dDZqsPvXKKyS1bvU2z5ElpKNJ4xQlOMUs/1+suA+j+kj5nAAya+VmT5HUKZmazluxVQ==" crossorigin="anonymous"></script>

关于javascript - 将线和点与折线图中的 x 轴值对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67077676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com