Advertisement
NTahmid

scatter_labels_legends

Mar 22nd, 2024
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 8.32 KB | None | 0 0
  1. <!doctype html>
  2. <meta charset="utf-8" />
  3. <html>
  4.   <head>
  5.     <script src="https://d3js.org/d3.v6.min.js" charset="utf-8"></script>
  6.     <script src="https://rawgit.com/susielu/d3-annotation/master/d3-annotation.min.js"></script>
  7.   </head>
  8.  
  9.   <style>
  10.     * {
  11.       font-family: sans-serif;
  12.     }
  13.  
  14.     #tooltip {
  15.       visibility: hidden;
  16.       position: absolute;
  17.       opacity: 0.8;
  18.       padding: 10px;
  19.       vertical-align: middle;
  20.       border-radius: 5px;
  21.       background-color: #ecf0f1;
  22.       font-size: 14px;
  23.     }
  24.  
  25.     .textbox {
  26.       font-size: 14px;
  27.     }
  28.  
  29.     #legend {
  30.       opacity: 0.2;
  31.       fill: #2c3e50;
  32.     }
  33.  
  34.     #title {
  35.       text-anchor: middle;
  36.       font-size: 22px;
  37.     }
  38.  
  39.     .label {
  40.       text-anchor: middle;
  41.     }
  42.  
  43.     #svg {
  44.       background-color: white;
  45.     }
  46.  
  47.     .annotation-group {
  48.       fill: #c86984;
  49.       stroke: #c86984;
  50.     }
  51.   </style>
  52.  
  53.   <body>
  54.     <div id="container" align="center"></div>
  55.  
  56.     <script type="text/javascript">
  57.       // Url to the input data
  58.       var url =
  59.         "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/cyclist-data.json";
  60.  
  61.       // Colors to differentiate riders with and without doping allegations
  62.       var colors = ["#27ae60", "#8e44ad"];
  63.  
  64.       // The attributes of the riders corresponding to the above colors
  65.       var legendKeys = ["No Doping Allegations", "Doping Allegations"];
  66.  
  67.       // Create an invisible div for the tooltip
  68.       const tooltip = d3
  69.         .select("body")
  70.         .append("div")
  71.         .attr("id", "tooltip")
  72.         .style("visibility", "hidden");
  73.  
  74.       // 1. Load the data from external source
  75.       d3.json(url).then(function (data) {
  76.         // 2. Append svg-object for the bar chart to a div in your webpage
  77.         // (here we use a div with id=container)
  78.         var width = 700;
  79.         var height = 500;
  80.         var margin = { left: 90, top: 80, bottom: 50, right: 20 };
  81.         var axisOffset = 10; // How for the axes are moved away from each other
  82.  
  83.         const svg = d3
  84.           .select("#container")
  85.           .append("svg")
  86.           .attr("id", "svg")
  87.           .attr("width", width)
  88.           .attr("height", height);
  89.  
  90.         // 3. Define scales to translate domains of the data to the range of the svg
  91.         var xMin = d3.min(data, (d) => d["Year"]);
  92.         var xMax = d3.max(data, (d) => d["Year"]);
  93.  
  94.         var parseTime = d3.timeParse("%M:%S");
  95.         var yMin = d3.min(data, (d) => parseTime(d["Time"]));
  96.         var yMax = d3.max(data, (d) => parseTime(d["Time"]));
  97.  
  98.         var xScale = d3
  99.           .scaleLinear()
  100.           .domain([xMin, xMax])
  101.           .range([margin.left + axisOffset, width - margin.right]);
  102.  
  103.         var yScale = d3
  104.           .scaleTime()
  105.           .domain([yMax, yMin])
  106.           .range([height - margin.bottom - axisOffset, margin.top]);
  107.  
  108.         // 4. Draw and transform/translate horizontal and vertical axes
  109.         var xAxis = d3.axisBottom().scale(xScale).tickFormat(d3.format("d"));
  110.         var yAxis = d3
  111.           .axisLeft()
  112.           .scale(yScale)
  113.           .tickFormat(d3.timeFormat("%M:%S"));
  114.  
  115.         svg
  116.           .append("g")
  117.           .attr("transform", "translate(0, " + (height - margin.bottom) + ")")
  118.           .attr("id", "x-axis")
  119.           .call(xAxis);
  120.  
  121.         svg
  122.           .append("g")
  123.           .attr("transform", "translate(" + margin.left + ", 0)")
  124.           .attr("id", "y-axis")
  125.           .call(yAxis);
  126.  
  127.         // 5. Draw individual scatter points and define mouse events for the tooltip
  128.         svg
  129.           .selectAll("scatterPoints")
  130.           .data(data)
  131.           .enter()
  132.           .append("circle")
  133.           .attr("cx", (d) => xScale(d["Year"]))
  134.           .attr("cy", (d) => yScale(parseTime(d["Time"])))
  135.           .attr("r", 5)
  136.           .attr("fill", (d) => (d["Doping"] == "" ? colors[0] : colors[1]))
  137.           .attr("class", "dot")
  138.           .attr("data-xvalue", (d) => d["Year"])
  139.           .attr("data-yvalue", (d) => parseTime(d["Time"]))
  140.           .on("mouseover", function (d) {
  141.             info = d["originalTarget"]["__data__"];
  142.             tooltip
  143.               .style("visibility", "visible")
  144.               .style("left", event.pageX + 10 + "px")
  145.               .style("top", event.pageY - 80 + "px")
  146.               .attr("data-year", info["Year"])
  147.               .html(
  148.                 info["Name"] +
  149.                   " (" +
  150.                   info["Year"] +
  151.                   ") <br> Time: " +
  152.                   info["Time"] +
  153.                   "<br><br>" +
  154.                   info["Doping"]
  155.               );
  156.           })
  157.           .on("mousemove", function () {
  158.             tooltip.style("left", event.pageX + 10 + "px");
  159.           })
  160.           .on("mouseout", function () {
  161.             tooltip.style("visibility", "hidden");
  162.           });
  163.  
  164.         // 6. Finalize chart by adding title, axes labels and legend
  165.        
  166.         //X-axis label
  167.         svg
  168.           .append("text")
  169.           .attr("x", margin.left + (width - margin.left - margin.right) / 2)
  170.           .attr("y", height - margin.bottom / 5)
  171.           .attr("class", "label")
  172.           .text("Year");
  173.  
  174.  
  175.         //Y-axis label
  176.         svg
  177.           .append("text")
  178.           .attr("y", margin.left / 4)
  179.           .attr("x", -height / 2)
  180.           .attr("transform", "rotate(-90)")
  181.           .attr("class", "label")
  182.           .text("Time to finish");
  183.  
  184.         //Title of the chart
  185.         svg
  186.           .append("text")
  187.           .attr("x", margin.left + (width - margin.left - margin.right) / 2)
  188.           .attr("y", margin.top / 2.6)
  189.           .attr("id", "title")
  190.           .text("Doping in professional bike racing");
  191.  
  192.         svg
  193.           .append("text")
  194.           .attr("x", margin.left + (width - margin.left - margin.right) / 2)
  195.           .attr("y", margin.top / 1.4)
  196.           .text("35 fastest times to finish Alpe d'Huez")
  197.           .style("font-size", "16px")
  198.           .style("text-anchor", "middle");
  199.  
  200.         //Chart Legends
  201.         svg
  202.           .selectAll("legendSymbols")
  203.           .data(legendKeys)
  204.           .enter()
  205.           .append("circle")
  206.           .attr("cx", width - margin.right - 200)
  207.           .attr("cy", (d, i) => 150 + i * 25)
  208.           .attr("r", 5)
  209.           .attr("fill", (d, i) => colors[i]);
  210.  
  211.         svg
  212.           .selectAll("legendTexts")
  213.           .data(legendKeys)
  214.           .enter()
  215.           .append("text")
  216.           .text((d) => d)
  217.           .attr("x", width - margin.right - 200 + 15)
  218.           .attr("y", (d, i) => 150 + i * 25 + 5)
  219.           .attr("class", "textbox");
  220.  
  221.         const legend = svg
  222.           .append("rect")
  223.           .attr("x", width - margin.right - 200 - 15)
  224.           .attr("y", 150 - 5 - 10)
  225.           .attr("rx", 5)
  226.           .attr("ry", 5)
  227.           .attr("width", 195)
  228.           .attr("height", 55)
  229.           .attr("id", "legend");
  230.  
  231.         // Annotations
  232.         const annotations = [
  233.           {
  234.             note: {
  235.               label: "Doping allegations and notable performances",
  236.               bgPadding: 20,
  237.               title: "Annotations"
  238.             },
  239.             color: ["#c86984"],
  240.             x: xScale(1995),
  241.             y: yScale(parseTime("36:50")),
  242.             dy: 50,
  243.             dx: 60,
  244.             subject: {
  245.               radius: 50,
  246.               radiusPadding: 5
  247.             },
  248.             type: d3.annotationCalloutCircle
  249.           }
  250.         ];
  251.  
  252.         const makeAnnotations = d3.annotation()
  253.           .annotations(annotations)
  254.           .type(d3.annotationLabel)
  255.           .accessors({
  256.             x: d => xScale(d.Year),
  257.             y: d => yScale(parseTime(d.Time))
  258.           })
  259.           .accessorsInverse({
  260.             Year: d => xScale.invert(d.x),
  261.             Time: d => yScale.invert(d.y)
  262.           })
  263.           .on('subjectover', function(annotation) {
  264.             annotation.type.a.selectAll("g.annotation-connector, g.annotation-note")
  265.               .classed("hidden", false);
  266.           })
  267.           .on('subjectout', function(annotation) {
  268.             annotation.type.a.selectAll("g.annotation-connector, g.annotation-note")
  269.               .classed("hidden", true);
  270.           });
  271.  
  272.         svg.append("g")
  273.           .attr("class", "annotation-group")
  274.           .call(makeAnnotations);
  275.       });
  276.     </script>
  277.   </body>
  278. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement