【问题标题】:How to run code and get required output on site "observablehq"如何在站点“observablehq”上运行代码并获得所需的输出
【发布时间】:2020-06-01 11:28:32
【问题描述】:

我是新的 d3.js。我正在尝试在此 link(observablehq) 运行代码。为了运行此代码,我将该代码放在 index.js 文件中。

d3 = require("d3@5")
height = 500
margin = ({top: 10, right: 10, bottom: 20, left: 40})
data = Object.assign(d3.csvParse(await FileAttachment("data.csv").text(), d3.autoType), {y: "Population"})
groupKey = data.columns[0]
keys = data.columns.slice(1)
x0 = d3.scaleBand()
    .domain(data.map(d => d[groupKey]))
    .rangeRound([margin.left, width - margin.right])
    .paddingInner(0.1)
x1 = d3.scaleBand()
    .domain(keys)
    .rangeRound([0, x0.bandwidth()])
    .padding(0.05)
y = d3.scaleLinear()
    .domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
    .rangeRound([height - margin.bottom, margin.top])
color = d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
xAxis = g => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x0).tickSizeOuter(0))
    .call(g => g.select(".domain").remove())
yAxis = g => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y).ticks(null, "s"))
    .call(g => g.select(".domain").remove())
    .call(g => g.select(".tick:last-of-type text").clone()
        .attr("x", 3)
        .attr("text-anchor", "start")
        .attr("font-weight", "bold")
        .text(data.y))
legend = svg => {
  const g = svg
      .attr("transform", `translate(${width},0)`)
      .attr("text-anchor", "end")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
    .selectAll("g")
    .data(color.domain().slice().reverse())
    .join("g")
      .attr("transform", (d, i) => `translate(0,${i * 20})`);

  g.append("rect")
      .attr("x", -19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", color);

  g.append("text")
      .attr("x", -24)
      .attr("y", 9.5)
      .attr("dy", "0.35em")
      .text(d => d);
}
chart = {
    const svg = d3.select(DOM.svg(width, height));

    svg.append("g")
        .selectAll("g")
        .data(data)
        .join("g")
        .attr("transform", d => `translate(${x0(d[groupKey])},0)`)
        .selectAll("rect")
        .data(d => keys.map(key => ({key, value: d[key]})))
        .join("rect")
        .attr("x", d => x1(d.key))
        .attr("y", d => y(d.value))
        .attr("width", x1.bandwidth())
        .attr("height", d => y(0) - y(d.value))
        .attr("fill", d => color(d.key));

    svg.append("g")
        .call(xAxis);

    svg.append("g")
        .call(yAxis);

    svg.append("g")
        .call(legend);

    return svg.node();
}

之后我从 html 脚本调用 index.js 文件

<!DOCTYPE html>
<html>
<head>
    <title>Visualization 2 (Multiline graph)</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://unpkg.com/d3@5.6.0/dist/d3.min.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script src="index.js"></script>
</body>
</html>

我从数组中创建了 data.csv 文件

State,Under 5 Years,5 to 13 Years,14 to 17 Years,18 to 24 Years,25 to 44 Years,45 to 64 Years,65 Years and Over
CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496
TX,2027307,3277946,1420518,2454721,7017731,5656528,2472223
NY,1208495,2141490,1058031,1999120,5355235,5120254,2607672
FL,1140516,1938695, 925060,1607297,4782119,4746856,3187797
IL,894368,1558919,725973,1311479,3596343,3239173,1575308
PA,737462,1345341,679201,1203944,3157759,3414001,1910571

此代码未提供 vizhub 中此图所需的输出。 如何获得所需的输出。这里是vizhub link to code

更新: 代码在 vizhub 中给了我以下错误

SyntaxError: Unexpected keyword 'const' (57:4)
/index.js (line 57)
53 :       .attr("dy", "0.35em")
54 :       .text(d => d);
55 : }
56 : chart = {
57 :     const svg = d3.select(DOM.svg(width, height));
         ^ 

【问题讨论】:

    标签: javascript d3.js svg observablehq


    【解决方案1】:

    首先要注意的是,在observablehq 上运行的 javascript 是一种不同风格的 js。它需要一个特殊的库运行时才能在您的浏览器上运行。因此,如果您将代码复制并粘贴到 .js .html 文件中,它将无法立即运行。

    Observable's Not Javascript

    如果您正在学习 d3 并喜欢 Observable 环境,您可以使用运行时轻松下载/嵌入您的代码。

    Downloading and Embedding Notebooks

    例如,从 observable 获取 notebook 代码,从 jsdelivr 获取运行时。 请记住,您可以下载源代码并从您自己的服务器上托管它。 下面的代码呈现单元格chart,运行时确保所有其他相关单元格按顺序执行。

    <div id="observablehq-758e3cb7"></div>
    <script type="module">
    import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js";
    import define from "https://api.observablehq.com/@d3/grouped-bar-chart.js?v=3";
    const inspect = Inspector.into("#observablehq-758e3cb7");
    (new Runtime).module(define, name => name === "chart" ? inspect() : undefined);
    </script>

    使用相同的方法但公开笔记本源代码,在这里您可以看到您的代码是如何在函数export default function notebook(runtime, observer) 中抽象出来的,然后运行时负责运行它,最后两行

        const runtime = new Runtime();
        const main = runtime.module(notebook, Inspector.into(document.body));
    

    <script type="module">
    
    import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js";
    
    // https://observablehq.com/@d3/grouped-bar-chart@81
    export default function notebook(runtime, observer) {
      const main = runtime.module();
      const fileAttachments = new Map([["data.csv","https://static.observableusercontent.com/files/72eda648679b19ee477d3b70a598c977219672ab0c809bd42a0e15fb322894dc78dead25bd50ad1613de459d161dc6278b3add8d5f251547b393b10c4cf00a05"]]);
      main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
      main.variable(observer()).define(["md"], function(md){return(
    md`# Grouped Bar Chart`
    )});
      main.variable(observer("chart")).define("chart", ["d3","DOM","width","height","data","x0","groupKey","keys","x1","y","color","xAxis","yAxis","legend"], function(d3,DOM,width,height,data,x0,groupKey,keys,x1,y,color,xAxis,yAxis,legend)
    {
      const svg = d3.select(DOM.svg(width, height));
    
      svg.append("g")
        .selectAll("g")
        .data(data)
        .join("g")
          .attr("transform", d => `translate(${x0(d[groupKey])},0)`)
        .selectAll("rect")
        .data(d => keys.map(key => ({key, value: d[key]})))
        .join("rect")
          .attr("x", d => x1(d.key))
          .attr("y", d => y(d.value))
          .attr("width", x1.bandwidth())
          .attr("height", d => y(0) - y(d.value))
          .attr("fill", d => color(d.key));
    
      svg.append("g")
          .call(xAxis);
    
      svg.append("g")
          .call(yAxis);
    
      svg.append("g")
          .call(legend);
    
      return svg.node();
    }
    );
      main.variable(observer("legend")).define("legend", ["width","color"], function(width,color){return(
    svg => {
      const g = svg
          .attr("transform", `translate(${width},0)`)
          .attr("text-anchor", "end")
          .attr("font-family", "sans-serif")
          .attr("font-size", 10)
        .selectAll("g")
        .data(color.domain().slice().reverse())
        .join("g")
          .attr("transform", (d, i) => `translate(0,${i * 20})`);
    
      g.append("rect")
          .attr("x", -19)
          .attr("width", 19)
          .attr("height", 19)
          .attr("fill", color);
    
      g.append("text")
          .attr("x", -24)
          .attr("y", 9.5)
          .attr("dy", "0.35em")
          .text(d => d);
    }
    )});
      main.variable(observer("x0")).define("x0", ["d3","data","groupKey","margin","width"], function(d3,data,groupKey,margin,width){return(
    d3.scaleBand()
        .domain(data.map(d => d[groupKey]))
        .rangeRound([margin.left, width - margin.right])
        .paddingInner(0.1)
    )});
      main.variable(observer("x1")).define("x1", ["d3","keys","x0"], function(d3,keys,x0){return(
    d3.scaleBand()
        .domain(keys)
        .rangeRound([0, x0.bandwidth()])
        .padding(0.05)
    )});
      main.variable(observer("y")).define("y", ["d3","data","keys","height","margin"], function(d3,data,keys,height,margin){return(
    d3.scaleLinear()
        .domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
        .rangeRound([height - margin.bottom, margin.top])
    )});
      main.variable(observer("color")).define("color", ["d3"], function(d3){return(
    d3.scaleOrdinal()
        .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
    )});
      main.variable(observer("xAxis")).define("xAxis", ["height","margin","d3","x0"], function(height,margin,d3,x0){return(
    g => g
        .attr("transform", `translate(0,${height - margin.bottom})`)
        .call(d3.axisBottom(x0).tickSizeOuter(0))
        .call(g => g.select(".domain").remove())
    )});
      main.variable(observer("yAxis")).define("yAxis", ["margin","d3","y","data"], function(margin,d3,y,data){return(
    g => g
        .attr("transform", `translate(${margin.left},0)`)
        .call(d3.axisLeft(y).ticks(null, "s"))
        .call(g => g.select(".domain").remove())
        .call(g => g.select(".tick:last-of-type text").clone()
            .attr("x", 3)
            .attr("text-anchor", "start")
            .attr("font-weight", "bold")
            .text(data.y))
    )});
      main.variable(observer("data")).define("data", ["d3","FileAttachment"], async function(d3,FileAttachment){return(
    Object.assign(d3.csvParse(await FileAttachment("data.csv").text(), d3.autoType), {y: "Population"})
    )});
      main.variable(observer("groupKey")).define("groupKey", ["data"], function(data){return(
    data.columns[0]
    )});
      main.variable(observer("keys")).define("keys", ["data"], function(data){return(
    data.columns.slice(1)
    )});
      main.variable(observer("margin")).define("margin", function(){return(
    {top: 10, right: 10, bottom: 20, left: 40}
    )});
      main.variable(observer("height")).define("height", function(){return(
    500
    )});
      main.variable(observer("d3")).define("d3", ["require"], function(require){return(
    require("d3@5")
    )});
      return main;
    }
    
    const runtime = new Runtime();
    const main = runtime.module(notebook, Inspector.into(document.body));
    
    </script>

    现在如果您想手动将运行在 Observable 上的代码转换为 vanilla js,那么您可能需要查看其他参考,

    How to run a D3 example

    D3 example from Observable on my wordpress site

    observable to vanillajs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多