Почему я не могу отобразить график d3?

Я не могу отобразить график D3 на веб-странице.

Я могу отобразить сюжет, когда выбираю <body>. Однако я не могу отобразить график, когда выбираю, скажем, <div>.

Ниже приведены мои настройки:

plot.html

<!DOCTYPE html>
<html>
    <head>
      <meta charset = "UTF-8">
      <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
    
      <title>Protein Structure Analyzer</title>
      <script type = "text/javascript" src = "../static/jquery/jquery-3.6.3.js"></script>
      <script type = "text/javascript" src = "../static/d3/d3.js"></script>
      <script type = "text/javascript" src = "../static/d3/d3.min.js"></script>
    </head>
    <body>
    <script type = "text/javascript">
    // set the dimensions and margins of the graph
    var margin = {top: 10, right: 40, bottom: 30, left: 30},
        width = 450 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;
    
    // append the svg object to the body of the page
    var svG = d3.select("#plot-div")
      .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 + ")");
    
    // Create data
    var data = [ {x:10, y:20}, {x:40, y:90}, {x:80, y:50} ]
    
    // X scale and Axis
    var x = d3.scaleLinear()
        .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
        .range([0, width]);       // This is the corresponding value I want in Pixel
    svG
      .append('g')
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));
    
    // X scale and Axis
    var y = d3.scaleLinear()
        .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
        .range([height, 0]);       // This is the corresponding value I want in Pixel
    svG
      .append('g')
      .call(d3.axisLeft(y));
    
    // Add 3 dots for 0, 50 and 100%
    svG
      .selectAll("whatever")
      .data(data)
      .enter()
      .append("circle")
        .attr("cx", function(d){ return x(d.x) })
        .attr("cy", function(d){ return y(d.y) })
        .attr("r", 7)
    </script>
    <div id = "plot-div"></div>
    </body>
</html>

Что я делаю неправильно?

DIV должен быть в документе до запуска сценария, поэтому просто переместите DIV в верхнюю часть документа.

Mark McClure 19.02.2023 00:38

@MarkMcClure, не работает.

user366312 19.02.2023 12:15

@user366312 user366312 Конечно, у меня работает. Единственные различия между вашим кодом и кодом, который я получил в своем ответе, - это используемая версия D3, тот факт, что я загружаю D3 только один раз, и тот факт, что скрипт загружается первым, как я уже упоминал.

Mark McClure 19.02.2023 12:28
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
2
3
65
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

DIV должен быть в документе до запуска скрипта, поэтому просто переместите DIV в начало документа:

// set the dimensions and margins of the graph
var margin = {top: 10, right: 40, bottom: 30, left: 30},
    width = 450 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svG = d3.select("#plot-div")
  .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 + ")");

// Create data
var data = [ {x:10, y:20}, {x:40, y:90}, {x:80, y:50} ]

// X scale and Axis
var x = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([0, width]);       // This is the corresponding value I want in Pixel
svG
  .append('g')
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// X scale and Axis
var y = d3.scaleLinear()
    .domain([0, 100])         // This is the min and the max of the data: 0 to 100 if percentages
    .range([height, 0]);       // This is the corresponding value I want in Pixel
svG
  .append('g')
  .call(d3.axisLeft(y));

// Add 3 dots for 0, 50 and 100%
svG
  .selectAll("whatever")
  .data(data)
  .enter()
  .append("circle")
    .attr("cx", function(d){ return x(d.x) })
    .attr("cy", function(d){ return y(d.y) })
    .attr("r", 7)
<script src = "https://code.jquery.com/jquery-3.6.3.min.js" integrity = "sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU = " crossorigin = "anonymous"></script>
<script type = "text/javascript" src = "https://d3js.org/d3.v7.min.js"></script>
<div id = "plot-div"></div>

Другие вопросы по теме