【问题标题】:How to create circles using CSV height, weight, radius and colors in d3如何在 d3 中使用 CSV 高度、重量、半径和颜色创建圆圈
【发布时间】:2020-04-12 14:01:00
【问题描述】:

我有高度、重量、半径和颜色的 CSV 数据。

我正在尝试使用这些数据制作圆圈,但什么也没得到(一个白色窗口)

这是代码:

<script src="https://d3js.org/d3.v5.min.js"></script>

<!DOCTYPE HTML>
<HTML>
<head>
    <meta charset="utf-8" />
    <title>companies</title>
    <style>
    svg {
        background-color: gray;
        height: 400px;
        width: 800px;
    }
</style>
</head>
<body>
<script>
           d3.csv("company.csv", function (the_data) {build_viz(the_data);});

        function build_viz(the_data) {
                    d3.select("svg")
                        .selectAll("circles")
                        .data(the_data)
                        .enter()
                        .append('circle')
                        .attr('cx', function (d) { return d.X; })
                        .attr('cy', function (d) { return d.Y; })
                        .attr('r', function (d) { return d.radius; })
                       .style("background-color", function (d) { return d.color; });
    }

    </script>
</body>

你知道这里缺少什么吗? 谢谢!

【问题讨论】:

    标签: javascript html css d3.js


    【解决方案1】:

    假设您的 company.csv 喜欢

    X,Y,半径

    100,20,10

    150,80,10

    <!DOCTYPE HTML>
    <HTML>
    
    <head>
        <meta charset="utf-8" />
        <title>companies</title>
        <style>
            .svg {
                background-color: gray;
                height: 400px;
                width: 800px;
            }
        </style>
        <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    
    <body>
        <svg class='svg'></svg>
        <script>
    
    
            d3.csv('./company.csv', function (the_data) {
                console.log("X", the_data.X)
                console.log("radius", the_data.radius)
                build_viz(the_data);
            });
    
            function build_viz(the_data) {
    
                d3.select('.svg')
                    .append("circle")
                    .attr("cx", the_data.X)
                    .attr("cy", the_data.Y)
                    .attr("r", the_data.radius)
                    .attr('fill', 'red')
            }
    
        </script>
    </body>
    

    输出:

    【讨论】:

    • 谢谢!我已经更正了代码(仅没有 log.console),它适用于实时服务器。现在我需要使用 on() 函数添加带有鼠标悬停的标签。见上面的代码。你知道这里要改什么吗?
    • 如果您更改了问题,请在新帖子下提问,因为其他人可以从您的第一个问题中受益。如果我的回答对第一个问题来说已经足够了,别忘了为其他用户确认我的回答。
    【解决方案2】:

    页面正文中没有svg 元素。

    因此,d3.select("svg") 返回一个空选择,因此圆圈不会附加到任何内容。

    通过在&lt;body&gt;之前脚本中添加以下内容来修复:

    <svg width="800px" height="400px"></svg>
    

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 2019-05-17
      • 2013-12-19
      • 1970-01-01
      • 2013-04-05
      • 2012-11-13
      • 2018-03-29
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多