如何在 Y 轴上获取虚线以及如何在 d3 中在图形旁边显示值

How to get a dashed line on Y axis and how to display the value beside the graph in d3

本文关键字:图形 显示 d3 获取 虚线      更新时间:2023-09-26

我是 D3 的新手,我编写了以下脚本来显示条形图。但是,我还需要做三件事

1) Get a dashed line on Y-axis
2) Increase spacing between the graphs
3) Display Value beside the end of the bar graph

这是我下面的代码 -

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.chart div {
    font: 10px sans-serif;
    background-color: steelblue;
    text-align: right;
    padding: 3px;
    margin: 1px;
    color: white;
}
</style>
<div class="chart"></div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
    //var data = [4, 8, 15, 16, 23, 42];
    var data = [ {
        "label" : "You ",
        "value" : 60
    }, {
        "label" : " Recommended",
        "value" : 60
    }, {
        "label" : "Peers",
        "value" : 40
    } ];
    var color = d3.scale.ordinal().range(
            [ "#8BA870", "#000000", "#FF8040", "#ff8c00" ]);
    var barPad = 10;
//  var x = d3.scale.linear().domain([ 0, d3.max(data)]).range([ 0, 420 ]);
    var x = d3.scale.linear().domain([0, 1000]).range([0, 1000]);
    d3.select(".chart").selectAll("div").data(data).enter().append("div")
    .style({stroke: "black", "stroke-width": "2px"})
    .style("height", function(d) { return 20+"px"; })
    .style("font-size","20px")
    .style("width", function(d) {
        return (d.value+100) + "px";
    }).style("background-color", function(d, i) {
        return color(i);
    }).text(function(d, i) {
        return data[i].label;
    });
</script>

你可以做这样的事情:

用于制作 Y 轴

d3.select(".chart").selectAll("div").data(data).enter()
.append("div")
.style("width","1px")
.style("height",height*2 + "px")
.style("padding-top","0.1px")
.style("padding","0.1px")
.style("background-color","black")

用于制作酒吧

.append("div")
.style({stroke: "black", "stroke-width": "2px"})
.style("height", function(d) { return height+"px"; })
.style("font-size","20px")
.style("margin-top","10px")
.style("text-align","left")
.style("width", function(d) {
    return (d.value+100) + "px";
}).style("background-color", function(d, i) {
    return color(i);
}).text(function(d, i) {
    return data[i].label;
})

为了使文本@成为栏的末尾:

.append("p")
.style("margin-top", function(d) {
    return -height -5 + "px";
})
.style("margin-left", function(d) {
    return (d.value+100) +10 + "px";
})
.style("color","black")
.text(function(d){ return d.value});

工作代码在这里

线的描边宽度

svg.append("path")
       .datum(data1)
       .attr("class", "line blue")
       .attr("stroke-width", "3px")
       .attr("d", line1);