Mapping custom colors to paths in D3 Sunburst visualizations can add a vibrant and unique touch

Currently, I am in the process of developing a D3 Sunburst Vue component and utilizing the npm package vue-d3-sunburst for this purpose. To access the documentation for the package, please visit:

https://www.npmjs.com/package/vue-d3-sunburst

The documentation mentions a get-category-for-color function that is utilized to associate an item with its color as follows:

(nodeD3: Object) => category: Number | String By default use the node name

I seem to be struggling at the moment trying to extract the color value of each node that is applied to every path. Can anyone assist me with this?

const {
  sunburst,
  highlightOnHover
} = window['vue-d3-sunburst'];
window.Vue.config.productionTip = false;

/**
 * FlavorWheel Component.
 */
new window.Vue({
  el: "#app",
  name: "flavor-wheel",
  components: {
    highlightOnHover,
    sunburst,
  },
  props: {
    /**
     * Cupping notes.
     */
    cuppingNotes: {
      type: Object,
      default () {
        return {
          name: "base",
          children: [{
              name: "Fruity",
              color: "#da1f24",
              children: [{
                  name: "Berry",
                  color: "#de4b52",
                  children: [{
                      name: "Blackberry",
                      color: "#3e0316",
                      size: 1,
                    },
                    {
                      name: "Blueberry",
                      color: "#6469af",
                      size: 1,
                    },
                  ],
                },
                {
                  name: "Dried fruit",
                  color: "#ca4a44",
                  children: [{
                      name: "Raisin",
                      color: "#b43b54",
                      size: 1,
                    },
                    {
                      name: "Prune",
                      color: "#a4456e",
                      size: 1,
                    },
                  ],
                },
                {
                  name: "Other fruit",
                  color: "#f2684b",
                  children: [{
                      name: "Cherry",
                      color: "#e73351",
                      size: 1,
                    },
                    {
                      name: "Pineapple",
                      color: "#f99a18",
                      size: 1,
                    },
                    {
                      name: "Peach",
                      color: "#f68a5b",
                      size: 1,
                    },
                  ],
                },
              ],
            },
            {
              name: "Sour/Fermented",
              color: "#ebb20f",
              children: [{
                name: "Sour",
                color: "#e1c217",
                children: [{
                    name: "Alcohol/Fermented",
                    color: "#9fa81a",
                    size: 1,
                  },
                  {
                    name: "Citric acid",
                    color: "#f9ee01",
                    size: 1,
                  },
                ],
              }, ],
            },
          ],
        };
      },
    },
  },
  data() {
    return {
      data: this.cuppingNotes,
    };
  },
  methods: {
    /**
     * A function used to map an item and its color
     */
    getColorValue() {},
  },
  template: `
    <div class="container">
      <sunburst
        class="flavor-wheel"
        :data="data"
        :showLabels="true"
        :centralCircleRelativeSize="10"
        :getCategoryForColor="getColorValue()"
      >
        <template slot-scope="{ on, actions }">
          <highlightOnHover v-bind="{ on, actions }" />
        </template>
      </sunburst>
    </div>
  `
});
.flavor-wheel {
  width: 500px !important;
  height: 500px !important;
  margin: 0 auto;
}

.flavor-wheel text {
  fill: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="285e5d4d054c1b055b5d464a5d5a5b5c681906110619">[email protected]</a>/dist/vue-d3-sunburst.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88e8d9dd59ccbd58b8d969a8d8a8b8cb8c9d6c1d6c9">[email protected]</a>/dist/vue-d3-sunburst.css">


<div id="app"></div>

Answer №1

While my knowledge of Vue is not extensive, I believe the issue can be explained as follows:

The problem lies in calling the function within the HTML, instead of passing it as a property. By adding brackets, you end up passing the result of the function to VueJS, rather than the function itself. This way, you can access the function's arguments as expected.


UPDATE

The name getCategoryForColor should have given me a clue, but the actual behavior is different from what one might anticipate. The getCategoryForColor function expects any string or value representing the "category" of the cell. These categories are then assigned colors using a colorScale function that ensures all elements belonging to the same category receive the same color value.

You got ahead of yourself a bit there because you already specified the color! To rectify this aspect, I modified the color scheme to simply return the passed value. As a result, the correct colors are now being applied.

const {
  sunburst,
  highlightOnHover
} = window['vue-d3-sunburst'];
window.Vue.config.productionTip = false;

/**
 * FlavorWheel Component.
 */
new window.Vue({
  el: "#app",
  name: "flavor-wheel",
  components: {
    highlightOnHover,
    sunburst,
  },
  props: {
    /**
     * Cupping notes.
     */
    cuppingNotes: {
      type: Object,
      default () {
        return {
          name: "base",
          children: [{
              name: "Fruity",
              color: "#da1f24",
              children: [{
                  name: "Berry",
                  color: "#de4b52",
                  children: [{
                      name: "Blackberry",
                      color: "#3e0316",
                      size: 1,
                    },
                    {
                      name: "Blueberry",
                      color: "#6469af",
                      size: 1,
                    },
                  ],
                },
                {
                  name: "Dried fruit",
                  color: "#ca4a44",
                  children: [{
                      name: "Raisin",
                      color: "#b43b54",
                      size: 1,
                    },
                    {
                      name: "Prune",
                      color: "#a4456e",
                      size: 1,
                    },
                  ],
                },
                {
                  name: "Other fruit",
                  color: "#f2684b",
                  children: [{
                      name: "Cherry",
                      color: "#e73351",
                      size: 1,
                    },
                    {
                      name: "Pineapple",
                      color: "#f99a18",
                      size: 1,
                    },
                    {
                      name: "Peach",
                      color: "#f68a5b",
                      size: 1,
                    },
                  ],
                },
              ],
            },
            {
              name: "Sour/Fermented",
              color: "#ebb20f",
              children: [{
                name: "Sour",
                color: "#e1c217",
                children: [{
                    name: "Alcohol/Fermented",
                    color: "#9fa81a",
                    size: 1,
                  },
                  {
                    name: "Citric acid",
                    color: "#f9ee01",
                    size: 1,
                  },
                ],
              }, ],
            },
          ],
        };
      },
    },
  },
  data() {
    return {
      data: this.cuppingNotes,
    };
  },
  methods: {
    /**
     * Function used to map an item and its color
     */
    getColorValue(v) {
      return v.color;
    },
    colorScale(col) {
      return col;
    }
  },
  template: `
    <div class="container">
      <sunburst
        class="flavor-wheel"
        :data="data"
        :showLabels="true"
        :centralCircleRelativeSize="10"
        :getCategoryForColor="getColorValue"
        :colorScale="colorScale"
      >
        <template slot-scope="{ on, actions }">
          <highlightOnHover v-bind="{ on, actions }" />
        </template>
      </sunburst>
    </div>
  `
});
.flavor-wheel {
  width: 500px !important;
  height: 500px !important;
  margin: 0 auto;
}

.flavor-wheel text {
  fill: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0b081850194e500e08131f080f0e093d4c5344534c">[email protected]</a>/dist/vue-d3-sunburst.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="136566763e77203e60667d716661606753223d2a3d22">[email protected]</a>/dist/vue-d3-sunburst.css">


<div id="app"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered in Angular: FormBuilder provider not found

I am currently utilizing Angular 9. An error that I am encountering is as follows: No provider for FormBuilder This issue has been documented in numerous instances, with the common solution being to include the FormsModule in the app.module.ts file. F ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

What is the process of generating enum values using ES6 in Node.js?

Can JavaScript support enumerations with assigned integer values, similar to how other programming languages handle it? In C#, for instance, I can define an enum as follows: enum WeekDays { Monday = 0, Tuesday =1, Wednesday = 2, Thursday ...

Ways to navigate the user to various screens

I'm currently developing an app that navigates users to various sections using Vue 3 and the Vue router. However, I'm facing a challenge in displaying different pages. When trying to show a new page, it doesn't display as expected. It seems ...

Glass-pane or angular/HTML overlay on a designated element

Is there a way to create a glass-pane effect, like an hourglass symbol on a semi-transparent layer, within the boundaries of an HTML element E? The goal is to have the glass-pane only overlap the area within E's boundaries. When the glass-pane is ac ...

What is the best way to remove input focus when clicked away?

I am in the process of developing an application using next js, and I need assistance with designing a search field. The primary functionality I am looking to implement is displaying search suggestions when the user starts typing, but hiding them when the ...

Executing PHP scripts using Ajax

Check out the code snippet below: <?php //echo $this->Html->css(array('bootstrap', 'mark', 'style')); echo $this->Html->script(array('timer','swfobject','bootstrap.min.js')); // ...

Updating MySQL Status Using PHP and JavaScript

I have a list of tasks that users can add dynamically. Each task has a checkbox next to it, and when checked, the status of that task in the MySQL database should be updated. My initial approach was to include the following code: echo "<input type=&ap ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

Laravel vue infinite scroll failing to load additional content

I've been trying to implement the infinite scroll feature from Element UI in my app, but for some reason, it's just not working. Here's a snippet of my code: Code script // Your JavaScript code goes here ...

Move the div containing an <audio></audio> tag

Is it possible to drag a div with a width of 200px and an element into a droppable area, and once the div is dropped, have its size change according to the sound duration (e.g. 1px per second)? Check out this example on jsFiddle. Below is the code snipp ...

Blend jQuery fade in

I have two variables var $aa = $('#Adiv').find('li').has('class'); var $bb = $('#Bdiv'); Both variables should be faded in using fadeIn() $aa.fadeIn(); $bb.fadeIn(); If they have the same action, is it possible ...

Error: The value of 'PlacesService' property is not defined and cannot be read

I am working towards gathering a selection of locations that meet specific criteria by making a "routeRequest" and storing them. To achieve this, I aim to utilize Google Places to search for locations around the central point of my map. let map = new goog ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

There are no leaks displayed in Chrome Dev Tools, however, the Task Manager will show them until Chrome eventually crashes

Do you have a CPU-intensive application that you're working on? Check it out here: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880 It involves a Canvas on which various elements are constantly being drawn. Here's the HTML ...

Unable to transfer bootstrap form data from the view to the controller due to issues with bootstrap validations

Scenario I have integrated a bootstrap form into my codeigniter application with bootstrap validation to ensure data accuracy. I want the submit button to work properly so that users can successfully submit the form and be redirected to the action page ...

"Effortlessly Arrange Multiple Gridview Rows Using Checkbox Selection in jQuery Drag and Drop

Struggling with getting checkboxes clicked when a GridViewRow becomes selected. Utilizing jQuery Methods like .sortable and .selectable. Worked as intended but looking to have a checkmark placed on the checkbox cbBulkSort within the GridView's first c ...

Retrieve data from MongoDB using the unique identifier (_id) and additional conditions with Express

Below is the code I am currently working with: PostCategory.find({categoryid:category._id.str},function(err,postcategories){ if(err) return next(err); Post.find({_id:postcategories.postid},function(err,posts){ if(err) ...

Tips for monitoring a field within an angularJS factory

Within my web application, I am utilizing a factory. This factory contains an object named mapLayers. Within my controller, I am assigning this factory.mapLayers object to a variable on the scope called $scope.mapLayers and using ngRepeat to iterate over i ...

Exploring JSON with JavaScript

[ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] The data above represents a JSON object. var searchBarInput = TextInput. ...