Using Array Data Format to Customize Color in Highcharts Funnel Chart

I have included the funnel visualization code that I've been working on.

$(function() {
  var dataEx = [
      ['1 Visit', 352000],
      ['2 Visits', 88000],
      ['3+ Visits', 42000]
    ],
    len = dataEx.length,
    sum = 0,
    minHeight = 0.05,
    data = [];
    
   //Specify your percentage of prior visit value manually here:
   
   var perc = [100, 25, 48];

  for (var i = 0; i < len; i++) {
    sum += dataEx[i][1];
  }

  for (var i = 0; i < len; i++) {
    var t = dataEx[i],
      r = t[1] / sum;
    data[i] = {
      name: t[0],
      y: (r > minHeight ? t[1] : sum * minHeight),
      percent: perc[i],   // <----- this is manual input
//percent: Math.round(r * 100),    <--- this is mathematical
      label: t[1]
    }
  }
  console.log(dataEx, data)
  $('#container').highcharts({
    chart: {
      type: 'funnel',
      marginRight: 100,


      events: {
        load: function() {
          var chart = this;
          Highcharts.each(chart.series[0].data, function(p, i) {
          var bBox = p.dataLabel.getBBox()
            p.dataLabel.attr({
              x: (chart.plotWidth - chart.plotLeft) / 2,
              'text-anchor': 'middle',
              y: p.labelPos.y - (bBox.height / 2)
            })
          })
        },
        redraw: function() {
          var chart = this;
          Highcharts.each(chart.series[0].data, function(p, i) {
            p.dataLabel.attr({
              x: (chart.plotWidth - chart.plotLeft) / 2,
              'text-anchor': 'middle',
              y: p.labelPos.y - (bBox.height / 2)
            })
          })
        }
      },
    },

    title: {
      text: 'Guest Return Funnel',
      x: -50
    },
    tooltip: {
      //enabled: false
      formatter: function() {
        return '<b>' + this.key +
          '</b><br/>Percent of Prior Visit: '+ this.point.percent + '%<br/>Guests: ' + Highcharts.numberFormat(this.point.label, 0);
      }
    },
    plotOptions: {
      series: {


        allowPointSelect: true,
        borderWidth: 12,

        animation: {
          duration: 400
        },


        dataLabels: {
          enabled: true,

          connectorWidth: 0,
          distance: 0,

          formatter: function() {
            var point = this.point;
            console.log(point);
            return '<b>' + point.name + '</b> (' + Highcharts.numberFormat(point.label, 0) + ')<br/>' + point.percent + '%';
          },
          minSize: '10%',
          color: 'black',
          softConnector: true
        },

        neckWidth: '30%',
        neckHeight: '0%',
        width: '50%',
        height: '110%'


        //old options are as follows:

        //neckWidth: '50%',
        //neckHeight: '50%',
        //-- Other available options
        //height: '200'
        // width: pixels or percent
      }
    },
    legend: {
      enabled: false
    },
    series: [{
      name: 'Unique users',
      data: data
    }]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/funnel.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="width: 500px; height: 400px; margin: 0 auto"></div>

My goal is to manually change the color of each category (piece) of the funnel, such as red, orange, yellow. There are different ways to enter data into a Highcharts series, including:

[['CATEGORY', 'VALUE'], ... ['CATEGORY', 'VALUE']]

You can also use an array with names and values and specify properties like

color: "#00FF00" within it.

Perhaps using the second method of entering data into a series where you can specify color would work well.

However, how can I specify colors for the pieces while ensuring that the data processing algorithm scales appropriately when dealing with small values?

Is there a way to specify colors based on the current array of data in my code which includes categories and values?

Answer №1

To easily customize the color of your data points, you can assign a color value to each element in the dataEx array and then use it as the point color:

var dataEx = [
        ['1 Visit', 352000, 'red'],
        ['2 Visits', 88000, 'orange'],
        ['3+ Visits', 42000, 'yellow']
    ],
    len = dataEx.length,
    sum = 0,
    minHeight = 0.05,
    data = [];

//Manually set the percentage of prior visit value here:

var perc = [100, 25, 48];

for (var i = 0; i < len; i++) {
    sum += dataEx[i][1];
}

for (var i = 0; i < len; i++) {
    var t = dataEx[i],
        r = t[1] / sum;
    data[i] = {
        name: t[0],
        color: t[2],
        y: (r > minHeight ? t[1] : sum * minHeight),
        percent: perc[i], // <----- this here is manual input
        //percent: Math.round(r * 100),    <--- this here is mathematical
        label: t[1]
    }
}

Check out the live demo for implementation: https://jsfiddle.net/BlackLabel/8be3c1sm/

For more information on available options, refer to the API Reference: https://api.highcharts.com/highcharts/series.funnel.data.color

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

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

npm installation for phonegap failed due to shasum check discrepancy

I've attempted numerous times, but I keep encountering this error (shasum check failed) 4784 error Error: shasum check failed for C:\Users\FENGXI~1\AppData\Local\Temp\npm-7004-QbpFFte5\1387269030233-0.28223602287471 ...

Error encountered in NextJS middleware: NetworkError occurred while trying to retrieve resource

I'm currently working with a middleware setup in NextJS based on an old tutorial. The code provided in the tutorial seems to be functioning correctly, but when I implement the same code, I encounter a NetworkError. Upon further investigation, it appea ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

How can I make a DIV occupy the entire vertical space of the page?

I am working on a Google Maps application that takes up the majority of the screen. However, I need to reserve a strip at the top for a menu bar. How can I ensure that the map div fills the remaining vertical space without being pushed past the bottom of ...

Using regular expressions in JavaScript, eliminate all characters preceding a specified final character

I am attempting to eliminate all text that precedes the last character in a Regex pattern. For example: rom.com/run/login.php Would turn into: login.php Can someone guide me on how to achieve this using JavaScript? I have limited experience with regul ...

By implementing Async.parallel, I ensure that the lifetime of my parameter does not exceed the duration of the asynchronous calls in NodeJS when working with MongoDB

After analyzing the code and its asynchronous behavior, it appears that the 'recipeData' array may not persist long enough to handle the asynchronous callbacks. To mitigate this, I created a copy of the data in a global array. However, I am encou ...

What is the process for verifying a checkbox after it has been selected?

I simplified my code to make it easier to understand const [factor, setfactor] = useState(1); const [nullify, setNullify] = useState(1); const Price = 10; const Bonus = 15; const finalPrice = (Price * factor - Bonus) * nullify; // start ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

Creating a dynamic view using AJAX to track and monitor user activity

I am having trouble with the Django By Example tutorial when it comes to following users. I have been clicking the follow button but nothing happens. I have reviewed that section multiple times, even copied and pasted the code, but it still does not functi ...

Sending data without the use of jQuery to a Django view is what occurred

I am currently facing an issue with sending data via Ajax, as the variables input_text and rotate always seem to default to empty values (input_text='', rotate=0). When using request.POST['text'], I encounter a 500 error stating that re ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

Make the object rotate around a specified vector point

I have been trying to figure out how to make an object orbit around the vector coordinates 0,0,0. Specifically, if the object is at X300, Y50, Z200, I want it to revolve around 0,0,0 without changing the position on the Y axis. Math isn't my strong su ...

How come I am still able to use jQuery's clone(true, true) method even after leaving the function where it was originally called?

When I used jQuery's clone(true,true) method to clone an element and store it in a variable newElem within a function, everything seemed to work fine. However, I noticed that even after exiting the function, the newElem variable (where the clone is st ...

"Error encountered while attempting to make the entire row in AngularJS UI-Grid editable simultaneously

I am currently facing an issue while trying to make a whole row editable using ui-grid with AngularJs. If you could take a look at the coding in the provided plnkr link and let me know where I might have gone wrong, that would be really helpful. Click her ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

What is the best method to achieve a width of 100% for an element (textarea) that has unspecified borders and padding, while also including the borders and padding

Native borders for input controls in various browsers often look more visually appealing compared to those set with CSS. However, the thickness of these native borders and padding can vary across different browsers, making it difficult to predict beforehan ...

Is there a way to accomplish this without using settimeout?

Whenever the Like button is pressed, I want to trigger the loading process I expect to see LOAD_POST_SUCCESS immediately after LIKE_POST_SUCCESS Pressing the Like button should initiate the load process After LIKE_POST_SUCESS, I want to see LOAD_POST_SU ...

JavaScript Alert function doesn't wait for execution

I am facing an issue with my Signup page. After submitting the form, I use AJAX POST to send the data. The problem arises in the success function where an alert is triggered immediately without waiting for user input, leading to the execution of the next f ...

Creating a new tab within a window that is already open

I have an interesting challenge - I need to open a new tab in a window that was previously opened using window.open(). So, if the window is already open, I want to open a tab in that same window. I have attempted to reference the existing window to open a ...