Advertisement
NTahmid

bar_label_legend

Mar 22nd, 2024 (edited)
830
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 7.30 KB | None | 0 0
  1.  
  2. ```<!DOCTYPE html>
  3. <meta charset="utf-8">
  4.  
  5. <style>
  6. .axis line{
  7.       visibility:hidden;
  8.     }
  9.  
  10. .axis .domain {
  11.   display: none;
  12. }
  13.  
  14. .axis {
  15.       font: 13px sans-serif;
  16.     }
  17.  
  18.   .yUnits {
  19.     font: 14px sans-serif;
  20.   }
  21.  
  22.   .caption {
  23.     font: 12px sans-serif;
  24.   }
  25.  
  26. .chartDisplayTitle{
  27.   fill:#354B5F;
  28.   font-weight: bold;
  29.   font: 20px sans-serif;
  30. }
  31.  
  32. .annotation-line {
  33.   stroke: red;
  34.   stroke-width: 1.5px;
  35. }
  36.  
  37. .annotation-circle {
  38.   stroke: crimson;
  39.   fill: none;
  40.   stroke-width: 1.5px;
  41. }
  42.  
  43. .annotation-text {
  44.   fill: red;
  45.   font-size: 13px;
  46.   font-family: sans-serif;
  47. }
  48.  
  49. .annotation-rect {
  50.   fill: red;
  51.   opacity: 0.1;
  52. }
  53. </style>
  54.  
  55. <svg class="chart" width="960" height="590" aria-labelledby="graph-title" aria-describedby="graph-desc">
  56.     <title>GDP Growth Remains Broad Based</title>
  57.     <desc id="graph-desc">GDP Growth Remains Broad Based, with values for 2017 quarters 1-3.</desc>
  58.     <text transform="translate(10, 20)" class="chartDisplayTitle">Chart1</text>
  59.     <text id="graph-title" transform="translate(10, 45)" class="chartDisplayTitle">GDP Growth Remains Broad Based</text>
  60.     <text transform="translate(10, 70)" class="yUnits">Percentage points*</text>
  61.     <text transform="translate(10, 570)" class="caption">*Contribution to total gross domestic product (GDP) growth; seasonally adjusted annualized rate.</text>
  62.     <text transform="translate(10, 585)" class="caption">SOURCE: Bureau of Economic Analysis.</text>
  63. </svg>
  64.  
  65. <script src="https://d3js.org/d3.v4.min.js"></script>
  66. <script src="https://rawgit.com/susielu/d3-annotation/master/d3-annotation.min.js"></script>
  67. <script>
  68.  
  69. const regression = d3.regressionLinear()
  70.   .x(d => d.x)
  71.   .y(d => d.y)
  72.   .domain([0, 100]);
  73.  
  74. </script>
  75. <script>
  76.  
  77. var econ2 = [
  78.   {
  79.     "Category": "GDP",
  80.     "2017 Q1": 1.2,
  81.     "2017 Q2": 3.1,
  82.     "2017 Q3 First Estimate": 3.0
  83.   },
  84.   {
  85.     "Category": "Consumption",
  86.     "2017 Q1": 1.3,
  87.     "2017 Q2": 2.2,
  88.     "2017 Q3 First Estimate": 1.6
  89.  
  90.   },
  91.   {
  92.     "Category": "Nonresidential investment",
  93.     "2017 Q1": 0.9,
  94.     "2017 Q2": 0.8,
  95.     "2017 Q3 First Estimate": 0.5
  96.  
  97.   },
  98.   {
  99.     "Category": "Residential investment",
  100.     "2017 Q1": 0.4,
  101.     "2017 Q2": -0.3,
  102.     "2017 Q3 First Estimate": -0.2
  103.   },
  104.   {
  105.     "Category": "Inventories",
  106.     "2017 Q1": -1.5,
  107.     "2017 Q2": 0.1,
  108.     "2017 Q3 First Estimate": 0.7
  109.  
  110.   },
  111.   {
  112.     "Category": "Net exports",
  113.     "2017 Q1": 0.2,
  114.     "2017 Q2": 0.2,
  115.     "2017 Q3 First Estimate": 0.4
  116.  
  117.   },
  118.   {
  119.     "Category": "Government",
  120.     "2017 Q1": -0.1,
  121.     "2017 Q2": 0.0,
  122.     "2017 Q3 First Estimate": 0.0
  123.  
  124.   }
  125. ]
  126.  
  127. var svg = d3.select("svg"),
  128.     margin = {top: 80, right: 10, bottom: 80, left: 25},
  129.     width = svg.attr("width") - margin.left - margin.right,
  130.     height = svg.attr("height") - margin.top - margin.bottom,
  131.     g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  132.  
  133. var y = d3.scaleLinear()
  134.       .domain([-2, 4])
  135.       .range([height, 0]);
  136.  
  137. var x0 = d3.scaleBand()  
  138.       .rangeRound([0, width])
  139.       .paddingInner(0.1)
  140.       .paddingOuter(0.1);
  141.  
  142. var x1 = d3.scaleBand()  
  143.     .paddingOuter(0.25)
  144.     .paddingInner(0.15);
  145.  
  146. var z = d3.scaleOrdinal()
  147.         .range(["#BC151E", "#D3B178", "#354B5F"]);
  148.  
  149. const yAxis = d3.axisLeft(y).ticks(7);
  150.  
  151. var subCategories = Object.keys(econ2[0]).slice(1);
  152.  
  153. x0.domain(econ2.map( d =>  d.Category ));
  154.  
  155. x1.domain(subCategories).rangeRound([0, x0.bandwidth()])
  156.  
  157.   var selection = g.selectAll("g")
  158.     .data(econ2)
  159.     .enter().append("g")
  160.       .attr("transform", d => "translate(" + x0(d.Category) + ",0)" )
  161.     selection.selectAll("rect")
  162.      .data(function(d) { return subCategories.map(function(key) { return {key: key, value: d[key]}; }); })
  163.       .enter().append("rect")
  164.       .attr("x", d => x1(d.key) )
  165.       .attr("y", d => (d.value<0 ? y(0) : y(d.value)) )
  166.      .attr("width", x1.bandwidth())
  167.      .attr("height", d => Math.abs(y(d.value) - y(0)) )
  168.       .attr("fill", d => z(d.key) )
  169.     selection.selectAll("text")
  170.        .data(function(d) { return subCategories.map(function(key) { return {key: key, value: d[key]}; }); })
  171.         .enter().append("text")
  172.         .attr("x", d => x1(d.key) )
  173.         .attr("y", d => d.value<=0 ? y(0) - (y(4) - (Math.abs(y(d.value) - y(0)) + 20)) : y(d.value) - 10)
  174.        .style('fill', d => z(d.key))
  175.         .style('font-size', '1.25em')
  176.         .text(d => Number.parseFloat(d.value).toFixed(1))
  177.  
  178. g.append("g")
  179.     .attr("class", "axis")
  180.     .attr("transform", "translate(0," + height + ")")
  181.     .call(d3.axisBottom(x0))
  182.     .selectAll(".tick text")
  183.     .call(wrap, x0.bandwidth());
  184.  
  185. g.append('g')
  186. .call(yAxis)
  187.  
  188. g.append("line")
  189.     .attr("y1", y(0))
  190.     .attr("y2", y(0))
  191.     .attr("x1", 0)
  192.     .attr("x2", width)
  193.     .attr("stroke", "black");
  194.  
  195. var legend = g.append("g")
  196.       .attr("font-family", "sans-serif")
  197.       .attr("font-size", 13)
  198.       .attr("text-anchor", "end")
  199.     .selectAll("g")
  200.     .data(subCategories)
  201.     .enter().append("g")
  202.       .attr("transform", function(d, i) { return "translate(0," + i * 24 + ")"; });
  203.   legend.append("rect")
  204.       .attr("x", width - 142)
  205.       .attr("width", 8)
  206.       .attr("height", 8)
  207.       .attr("fill", z);
  208.   legend.append("text")
  209.           .attr("x", d => d.length > 7 ? (width + 5) : (width - 80))
  210.           .attr("y", 5.5)
  211.           .attr("dy", "0.22em")
  212.           .text(d => (d));
  213.  
  214.   function wrap(text, width) {
  215.             text.each(function() {
  216.               var text = d3.select(this),
  217.                   words = text.text().split(/\s+/).reverse(),
  218.                   word,
  219.                   line = [],
  220.                   lineNumber = 0,
  221.                   lineHeight = 1.1,
  222.                   y = text.attr("y"),
  223.                   dy = parseFloat(text.attr("dy")),
  224.                   tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
  225.               while (word = words.pop()) {
  226.                 line.push(word);
  227.                 tspan.text(line.join(" "));
  228.                 if (tspan.node().getComputedTextLength() > width) {
  229.                   line.pop();
  230.                   tspan.text(line.join(" "));
  231.                   line = [word];
  232.                   tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
  233.                 }
  234.               }
  235.             });
  236.           }
  237.  
  238. // Annotations
  239. var annotations = [
  240.   {
  241.     note: {
  242.       label: "GDP growth in Q2 and Q3",
  243.       title: "Highlight"
  244.     },
  245.     x: x0("GDP") + x1("2017 Q2"),
  246.     y: y(3.1),
  247.     dy: -30,
  248.     dx: 30
  249.   },
  250.   {
  251.     note: {
  252.       label: "Decrease in Residential investment in Q2",
  253.       title: "Outlier"
  254.     },
  255.     x: x0("Residential investment") + x1("2017 Q2"),
  256.     y: y(-0.3),
  257.     dy: 30,
  258.     dx: 30
  259.   }
  260. ];
  261.  
  262. var makeAnnotations = d3.annotation()
  263.   .annotations(annotations);
  264.  
  265. g.append("g")
  266.   .attr("class", "annotation-group")
  267.   .call(makeAnnotations);
  268.  
  269. // Highlighting
  270. g.selectAll(".highlight")
  271.   .data(econ2)
  272.   .enter().append("rect")
  273.   .attr("class", "highlight")
  274.   .attr("x", d => x0(d.Category))
  275.   .attr("width", x0.bandwidth())
  276.   .attr("y", 0)
  277.   .attr("height", height)
  278.   .attr("fill", "red")
  279.   .attr("opacity", d => d.Category === "GDP" || d.Category === "Residential investment" ? 0.1 : 0);
  280.  
  281. </script>```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement