oumaima
oumaima

Reputation: 71

Spring MVC: How to display Hashmap keys and values in highcharts

I want to display data from my database into highcharts (bars).

I tried using HashMap to pass values from controller to javascript.

MyController.java:

@GetMapping("/Hist")
public String barGraph(Model model) {

    ApplicationContext context = 
            new ClassPathXmlApplicationContext("Spring-Module.xml");

    PTS_POINTS_HISTORY_DAO ptsHistDAO = (PTS_POINTS_HISTORY_DAO) context.getBean("PtsPointsHistoryDAO");

    model.addAttribute("surveyMap", ptsHistDAO.barGraph());

     //ptsHistDAO.barGraph() returns Map<String, Integer>


    return "Hist";
}
hist.jsp:

<div id="containerx" style="width:100%; height:400px;"></div>
<script>

Highcharts.chart('containerx', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Total Redeem'
    },
    xAxis: {


        categories: ['${surveyMap.keySet()}']
    },
    yAxis: {
        max: 10000,
        min:0,
        title: {
            text: 'Numbre of Loylaty Points Redeemed'
        }
    },
    tooltip: {
        pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
        shared: true
    },
    plotOptions: {
        column: {
            stacking: 'permillion'
        }},
    series: [{
        name: 'Fulfilled',
        data: [9667, 0, 5694, 2752, 200]
    }, {
        name: 'Cancelled',
        data: [500, 3000, 300, 2, 1]
    }, {
        name: 'Pending',
        data: [3, 500, 400, 2, 50]
    }]
});

</script>

I expected that each key will be represented by their value in bar graph, but actually all the keys represents only the first value in graph.

expected : x1:20151514 y1: 9667 cancelled, 500 fullfilled, 3 pending what i get: x1: [20151514,20151513,20151512..] y1: 9667 cancelled, 500 fullfilled, 3 pending enter image description here

Upvotes: 0

Views: 557

Answers (1)

ppotaczek
ppotaczek

Reputation: 39109

Highcharts requires categories property to be an array of strings. Your result was a string, which required to use JSON.parse method:

var str = "[0013-05-08, 2010-11-17, 0015-05-09, 0024-01-01, 0021-01-01]"
var res = str.replace(/,\s/g, '","');
var res2 = res.replace('[', '["');
var res3 = res2.replace(']', '"]')

Highcharts.chart('container', {
    xAxis: {
        categories: JSON.parse(res3)
    },
    series: [{
        data: [1, 2, 3, 4, 5]
    }]
});

Live demo: http://jsfiddle.net/BlackLabel/k4L3whu5/

API Reference: https://api.highcharts.com/highcharts/xAxis.categories

Upvotes: 1

Related Questions