Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here:

https://i.stack.imgur.com/y5gL1.png

I have managed to achieve this with individual data points per label (non-stacked data), but when I switch to an array input, the data fails to render. This example is functional: https://jsfiddle.net/jakobhl/krx4e5pm/2/

var dataName = function(imgSrc) {
  return '<span><img src=' + imgSrc + ' ' + 'style="width: 40px; height: 40px;"/><br></span>';
};

var data2016 = [
  [11, dataName("https://image.flaticon.com/icons/svg/197/197571.svg")],
  [11, dataName("https://image.flaticon.com/icons/svg/197/197408.svg")],
  [11, dataName("https://image.flaticon.com/icons/svg/197/197375.svg")],
  [14, dataName("https://image.flaticon.com/icons/svg/197/197374.svg")],
  [12, dataName("https://image.flaticon.com/icons/svg/197/197484.svg")],
];


Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
    plotOptions: {
        column: {
            stacking: 'normal',
            dataLabels: {
                enabled: true
            }
        }
    },
  xAxis: {
    tickmarkPlacement: 'on',
    lineWidth: 0,
    type: 'category',
    labels: {
      useHTML: true,
      align: 'center'
    }
  },

  series: [{
    keys: ['y', 'name'],
    data: data2016,
  }]
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="container"></div>

However, the following does not work: https://jsfiddle.net/jakobhl/2rfa645x/3/

var dataName = function(imgSrc) {
  return '<span><img src=' + imgSrc + ' ' + 'style="width: 40px; height: 40px;"/><br></span>';
};

var data2016 = [
  [[11, 15], dataName("https://image.flaticon.com/icons/svg/197/197571.svg")],
  [[12, 15], dataName("https://image.flaticon.com/icons/svg/197/197408.svg")],
  [[13, 15], dataName("https://image.flaticon.com/icons/svg/197/197375.svg")],
  [[41, 15], dataName("https://image.flaticon.com/icons/svg/197/197374.svg")],
  [[11, 15], dataName("https://image.flaticon.com/icons/svg/197/197484.svg")],
];

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
    plotOptions: {
        column: {
            stacking: 'normal',
            dataLabels: {
                enabled: true
            }
        }
    },
  xAxis: {
    tickmarkPlacement: 'on',
    lineWidth: 0,
    type: 'category',
    labels: {
      useHTML: true,
      align: 'center'
    }
  },

  series: [{
    keys: ['y', 'name'],
    data: data2016,
  }]
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="container"></div>

Is there a way to stack the data by country while still using SVGs as labels?

Credits and thanks go to the jsfiddle user BlackLabel for the inspiration.

Answer №1

If you want to include a new value, make sure to adjust the data format that Highcharts requires. For instance, if the additional value is labeled as x, follow these steps:

var newData = [
    [
        11, 15, dataLabel("https://image.flaticon.com/icons/svg/197/197571.svg")
    ],
    ...
];


Highcharts.chart('container', {
    ...,
    series: [{
        keys: ['y', 'x', 'name'],
        data: newData
    }]
});

Check out this live demo: https://jsfiddle.net/BlackLabel/vubjn8od/

For more information, refer to the API Reference: https://api.highcharts.com/highcharts/series.column.keys

Answer №2

I never did figure out why the initial solution wasn't working, but I found a successful workaround by utilizing categories instead of series: Check it out here

var dataName = function(imgSrc) {
  return '<span><img src=' + imgSrc + ' ' + 'style="width: 40px; height: 40px;"/><br></span>';
};

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Stacked column chart'
    },
    xAxis: {
        labels: {
      useHTML: true,
      align: 'center'
    },
        categories: [dataName("https://image.flaticon.com/icons/svg/197/197571.svg"), dataName("https://image.flaticon.com/icons/svg/197/197408.svg"), dataName("https://image.flaticon.com/icons/svg/197/197375.svg"), dataName("https://image.flaticon.com/icons/svg/197/197374.svg"), dataName("https://image.flaticon.com/icons/svg/197/197484.svg")]
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total fruit consumption'
        },
        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: ( // theme
                    Highcharts.defaultOptions.title.style &&
                    Highcharts.defaultOptions.title.style.color
                ) || 'gray'
            }
        }
    },
    legend: {
        align: 'right',
        x: -30,
        verticalAlign: 'top',
        y: 25,
        floating: true,
        backgroundColor:
            Highcharts.defaultOptions.legend.backgroundColor || 'white',
        borderColor: '#CCC',
        borderWidth: 1,
        shadow: false
    },
    tooltip: {
        headerFormat: '<b>{point.x}</b><br/>',
        pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
    },
    plotOptions: {
        column: {
            stacking: 'normal',
            dataLabels: {
                enabled: true
            }
        }
    },
    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Jane',
        data: [2, 2, 3, 2, 1]
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5]
    }]
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="container"></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

I noticed that the node_modules folder has mysteriously vanished from my

When I tried running npm install in the terminal of VS Code. PS D:\work\backEnd> npm install npm WARN old lockfile npm WARN old lockfile The package-lock.json file was created with an older version of npm, npm WARN old lockfile so ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...

Could the comments within a NodeJS script be causing memory problems?

I specialize in creating NodeJS libraries, and my coding practice includes adding JSDoc comments for documentation purposes. Here is an example of how my code usually looks: /** * Sum * Calculates the sum of two numbers. * * @name Sum * @function * ...

Error message 'require is not defined' can occur in Meteor.js when trying to incorporate an NPM package

I'm facing an issue while trying to utilize an npm package in Meteor.js (Release 0.6.6.3) by using Meteor.require. The error thrown states that require is not defined. What could be causing this and how can it be resolved? mrt add npm npm install git ...

What is the best way to determine the left and top coordinates when resizing a draggable image within a container?

I am struggling to correctly scale the image and set the left (x) and top (y) positions. Here is the code from my template: <div id="container" :style="`height: ${height}px;width: ${size}px;overflow: hidden;position: relative;`"> ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

What is the best way to select the element where a user has clicked using JavaScript?

Referencing a previous question on Stack Overflow, the goal is to track user clicks in a Firefox browser using JavaScript. The provided JavaScript code almost achieves this: var DocElements = document.getElementsByTagName('*');for(var i = 0; i & ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Having trouble toggling between the trending and search features on giphy website

I've been developing a chat application with NextJS and I'm currently working on integrating GIPHY images into it. Although I have the basic setup in place, I'm facing issues when switching between the giphy.search() and giphy.trending() fu ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

Once the print dialog is canceled or saved, the current window remains open

Whenever I try to print the data, a new window opens displaying all the respective data of the HTML page. The print dialog then quickly appears, but if I cancel or close the dialog, the current window does not close. Can someone please provide suggestions ...

Setting up React Router in a nested directory with a flexible route structure

As a newcomer to react router, I am seeking guidance on setting it up in a specific scenario. Imagine we have a PHP application running on 'http://www.example.com'. Within this setup, there is a react application located at 'http://www.examp ...

The Vue computed property is failing to retrieve the data it needs

I'm having trouble with the computed() property not retrieving data. Data was initialized in the created() property. Am I missing something here? Any guidance on how to resolve this issue would be greatly appreciated. const randomPlayers = { temp ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

AngularJS: Advanced Routing for Dynamic Web Applications

Hello, I am currently exploring the possibility of implementing something similar to this code snippet using AngularJS: $routeProvider .when('/root/:controllerName/blah/:blahId/blah/:blah', { templateUrl: '/tmpl/:controllerName ...

Only output to the console if the data returned from an AJAX request has been

Here is a script that I created: <script type="text/javascript> $('.storage').html(""); setInterval(function(){ $.get('./playcommand.php', function(data) { if($('.storage').html() !== data){ ...

Utilize a button within a form to add additional variables to a URL that already contains variables from a separate form

I operate a website that features a search bar and checkboxes for adding variables to the URL: term = "test" variable1=1 url/search?term=test&variable1=1 After completing the initial search, I have additional forms on the left side of the page with m ...

The sonar scanner encountered an error while attempting to parse a file using the espree parser in module mode

While executing sonar-scanner on a node project, I encounter a Failed to parse file issue, as shown below: ERROR: Failed to parse file [file:///home/node-app/somedir/index.js] at line 1: Unexpected token './AddCat' (with espree parser in mod ...