General method and interface for creating a bar chart using highchart

Source: Internet
Author: User


This article provides a general method and interface for using highchart to draw a bar chart. You can use it directly by specifying the corresponding data structure and configuration.


I. data structure and basic interfaces

Generally, drawing a graph involves complicated data structures. For example, you can use jsPlumb to draw a topology. The method is to first figure out the data structure required for drawing a graph, then design a public interface according to the API documentation, and write a detailed document to avoid forgetting it in the future. Start with the most basic interface. See the following code. This is an interface that extracts the places where data needs to be dynamically generated or configured Based on the static example.

/*** Create a bar chart (basic interface) * @ param chartDivName is used to draw the DIV-ID value of the bar chart * @ param chartData column chart data structure * categories: ['c1 ', 'c2 ',..., 'cn'] * series: [* {name: 'var1', data: [d11, d12 ,..., d1n]}, * {name: 'var2', data: [d21, d22 ,..., d2n]}, *..., * {name: 'varn', data: [dn1, dn2 ,..., dnn]} *] * @ param chartConfig global bar chart configuration * title: chart title * @ returns */function generateColumnChart (chartDivName, chartData, chart Config) {var displayFormatter = function () {// when you hover the cursor over the chart, the formatting prompt information var tipText = '<B>' + this. x + '</B>'; var total = 0; $. each (this. points, function (I, point) {total + = point. y ;}); $. each (this. points, function (I, point) {tipText + = '<br/>' + point. series. name + ':' + Highcharts. numberFormat (point. y * 100/total), 2) + '%' + '(' + point. y + ')';}); return tipText;}; var chartObj = obtainCommonC HartObj (displayFormatter); chartObj. title. text = chartConfig. title; chartObj. xAxis. categories = chartData. categories; chartObj. series = chartData. series; var seriesNum = (chartData. series = null? 0: chartData. series. length); for (var k = 0; k <seriesNum; k ++) {chartObj. series [k]. type = 'column';} var chartdiv =$ ('#' + chartDivName); chartdiv. highcharts (chartObj);} function obtainCommonChartObj (displayFormatterFunc) {var commonChartObj = {chart: {zoomType: 'X', events: {click: null}, resetZoomButton: {position: {x:-10, y: 10}, relativeTo: 'chart' }}, // remove the link highcharts.com credits: {enabled: false, text: ''}, plotOptions: {series: {// remove the vertex marker to make the image more beautiful. marker: {enabled: false, states: {hover: {enabled: true }}, turboThreshold: 0, events: {click: null }}, line: {lineWidth: 1.5 }}, series: [], xAxis :{}, yAxis :{ title: {text :''}, min: 0}, tooltip: {crosshairs: true, shared: true, formatter: displayFormatterFunc}, title: {// The title text: '', align: 'center', style: {fontSize: '12px ', margin: '3px' }}; return commonChartObj ;}

Ii. Object array and Structure Conversion

Generally, the data structure returned from the backend of the server is an array of objects. To draw the data using basic interfaces, You need to convert the data structure. Therefore, you can build a high-level interface on top of the basic interface, as shown in the following code. If the data structure to be converted is complex, you can use a static input/output data example as a model to help you think about it. First, you can use excellent coding to achieve the goal, then, replace hard encoding with configurable items to achieve scalability and flexibility.

/*** Create a bar chart (a high-level interface for the object array) * @ param chartDivName is used to draw the DIV-ID value of the bar chart * @ param chartData object array * categories: ['c1 ', 'c2 ',..., 'cn'] * data: * [{'field1': 'v11', 'field2': 'v12 ',..., 'fielddn ': 'v1n'}, * {'field1': 'v21', 'field2': 'v22 ',..., 'fielddn': 'v2n '},*..., * {'field1': 'vn1 ', 'field2': 'vn2 ',..., 'fielddn': 'vnn '}] * @ param chartConfig global configuration * title: chart title * categoryField: Category field * groupField: The grouping field * valueField used to create a legend: field used to display the Y axis * @ returns */function generateColumnChartHighLevel (chartDivName, chartData, chartConfig) {var groupField = chartConfig. groupField; var valueField = chartConfig. valueField; var categoryField = chartConfig. categoryField; var categories = chartData. categories; var groupedChartData = groupByField (chartData. data, groupField); var series = []; for (var I = 0; I <GroupedChartData. length; I ++) {var groupName = groupedChartData [I] [groupField]; var groupData = groupedChartData [I] ['data']; var fieldData = []; for (var k = 0; k <groupData. length; k ++) {// The value of each category must correspond to the corresponding category. In this case, // For each groupField, not all categories have a value, it can be seen from the test example that the corresponding value of Apple in Q3 is missing, and the value of banana in Q2 is missing var categoryPosition = getCategoryPosition (categories, groupData [k] [categoryField]); if (categoryPos Ition! =-1) {fieldData [categoryPosition] = groupData [k] [valueField] ;}for (var j = 0; j <categories. length; j ++) {// if (fieldData [j] = null) {fieldData [j] = 0 ;}} var subseries = {name: groupName, data: fieldData,}; series. push (subseries) ;}var data ={}; data. categories = categories; data. series = series; generateColumnChart (chartDivName, data, chartConfig);}/*** check the position of value in categories * @ param Categories * @ param value */function getCategoryPosition (categories, value) {for (var index = 0; index <categories. length; index ++) {if (categories [index] = value) {return index;} return-1 ;} /*** classify the specified chartData data according to the value of the specified field * eg. [{'timestamp': 'time0', cpu: '0', sys: '15', usr: '20'}, {'timestamp': 'time0', cpu: '1', sys: '16', usr: '21'}, * {'timestamp': 'time1', cpu: '0', sys: '20 ', usr: '13 '}, {'Timestamp': 'time1', cpu: '1', sys: '18', usr: '10'}] * to [{cpu: '0 ', data: [{'timestamp': 'time0', cpu: '0', sys: '15', usr: '20'}, {'timestamp': 'time1 ', cpu: '0', sys: '20', usr: '13'}]}, * {cpu: '1', data: [{'timestamp ': 'time0', cpu: '1', sys: '16', usr: '21'}, {'timestamp': 'time1', cpu: '1', sys: '18', usr: '10'}] */var groupByField = function (chart0000athered, fieldName) {var fi EldDataMappingArray = []; var fieldData = {}; var I = 0, num = (chartpolicathered = null? 0: chartpolicathered. length); for (I = 0; I <num; I ++) {var fieldValue = chartDataGathered [I] [fieldName]; fieldData = obtainFieldData (fieldDataMappingArray, fieldName, fieldValue ); if (fieldData = null) {fieldData = {}; fieldData [fieldName] = fieldValue; fieldData ['data'] = []; fieldDataMappingArray. push (fieldData);} fieldData ['data']. push (chartDataGathered [I]);} return fieldDataMappingArray;}/*** in field Check whether fieldName = fieldValue object exists in DataMappingArray. If yes, return null * @ param fieldDataMappingArray [{'fieldname': 'fieldvalue1 ', 'data ': []}, {'fieldname': 'fieldvalue2', data: []}] * @ param fieldName the name of field * @ param fieldValue the value of field */var obtainFieldData = function (fieldDataMappingArray, fieldName, fieldValue) {var k = 0, dataArrayLength = (fieldDataMappingArray = null? 0: fieldDataMappingArray. length); var fieldData ={}; var existFieldData ={}; if (dataArrayLength = 0) {return null;} for (k = 0; k <dataArrayLength; k ++) {existFieldData = fieldDataMappingArray [k]; if (existFieldData [fieldName] = fieldValue) {return existFieldData ;}} return null ;}

Iii. interfaces used

<! Doctype html public "-// w3c // dtd html 4.01 // en" "http://www.w3.org/tr/html4/strict.dtd"> 

IV,

V. Summary

To draw a bar chart, you must have a good grasp of the data structure and algorithm, and be able to freely convert various data structures. In this example, we want to demonstrate the application of the structure and algorithm in actual development. Of course, the code given in this article is not optimal. As a basic solution, there are still many improvements.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.