Gradient coloring for D3 radial barplot

  d3.js, javascript

I’ve got a circular bar plot which I’m trying to color with a gradient but I can’t seem to figure it out. Most posts show gradients from outer to inner of the plot but I wanted a gradient that goes from right to left like this. enter image description here

Is this even possible with D3 or should I just try another library? Code below:

<head>
    <meta charset="UTF-8">
    <title>Visualizer Sample</title>
    <!-- Load d3.js -->
    <script src="https://d3js.org/d3.v4.js"></script>

    <!-- Function for radial charts -->
    <script src="https://cdn.jsdelivr.net/gh/holtzy/[email protected]/LIB/d3-scale-radial.js"></script>
</head>

Body

  <div id="my_dataviz">
  </div>

Script

// set the dimensions and margins of the graph
var margin = {top: 0, right: 10, bottom: 10, left: 10},
    width = 800 - margin.left - margin.right,
    height = 800 - margin.top - margin.bottom,
    innerRadius = 180,
    outerRadius = 3_000;   // the outerRadius goes from the middle of the SVG area to the border

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    // .attr("transform", "translate(" + width / 2 + "," + ( height/2+100 )+ ")"); // Add 100 on Y translation, cause upper bars are longer
    .attr('transform', `translate(400, ${height / 2 + 100})`)

d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/7_OneCatOneNum.csv", function(data) {

  // X scale
  var x = d3.scaleBand()
      .range([0, 2 * Math.PI])    // X axis goes from 0 to 2pi = all around the circle. If I stop at 1Pi, it will be around a half circle
      .align(0)                  // This does nothing ?
      .domain( data.map(function(d) { return d.Country; }) ); // The domain of the X axis is the list of states.

  // Y scale
  var y = d3.scaleRadial()
      .range([innerRadius, outerRadius])   // Domain will be define later.
      .domain([0, 5000]); // Domain of Y is from 0 to the max seen in the data

  // Add bars
  svg.append("g")
    .selectAll("path")
    .data(data)
    .enter()
    .append("path")
      .attr("fill", "RGB(76,83,87)")  // "#69b3a2")
      .attr("d", d3.arc()     // Imagine you're doing a part of a donut plot
          .innerRadius(innerRadius)
          .outerRadius(function(d) { return y(d.Value); })
          .startAngle(function(d) { return x(d.Country) - 0.002; })
          .endAngle(function(d) { return x(d.Country) + x.bandwidth(); })
          .padAngle(0)  // used to be padded 0.01
          .padRadius(innerRadius))

});

Source: Ask Javascript Questions

LEAVE A COMMENT