从折线图的字符串值(文本)制作 x 坐标

Making x coordinates from string values(text) for a line graph

本文关键字:制作 坐标 文本 折线图 字符串      更新时间:2023-09-26

我真的很努力学习d3,所以我希望你能帮助我解决这个问题。我想出了如何将数据缩放或映射到 y 坐标的 svg,因为该数据有数字。我将在下面向您展示我是如何做到的。但是对于 x 值,没有数字,只有像 1mo、2mo、3mo 这样的文本。等。。我想将它们转换为折线图的 x 坐标。它们应沿图形的宽度均匀分布。希望你能告诉我如何获取 x 坐标,以便我可以使用线生成器来创建路径。

    var data = [
        {"quarter" : "1mo", "votes" : 400},
        {"quarter" : "2mo", "votes": 200},
        {"quarter": "3mo", "votes" : 1000},
        {"quarter" : "4mo", "votes" : 600}
    ]
    var width = 600;
    var height = 300;
    //supposed to get the domain ([0, 1000])
    var yscale = d3.scale.linear().domain([0, d3.max(data, function(d) {return d.votes})])
    yscale.range([height, 0])
    console.log(yscale(30)) //291
    //now I need to get the x cordinates

您正在寻找 d3.scale.ordinal:

序数刻度具有离散域,例如一组名称或 类别。

var data = [
  {"quarter" : "1mo", "votes" : 400},
  {"quarter" : "2mo", "votes": 200},
  {"quarter": "3mo", "votes" : 1000},
  {"quarter" : "4mo", "votes" : 600}
],
  width = 600;
var x = d3.scale.ordinal()
  .domain( data.map(function(d){ return d.quarter }) ) //<-- a tick for every quarter
  .rangeBands([0, width], .1); //<-- across the range of our graph with 10% padding on outer ticks
console.log(x("1mo"));
console.log(x("4mo"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>