score:42
You can use jQuery.extend()
and Highcharts.setOptions
.
So first you'll make the first object which will be extended by all your charts, this object will contain your Highchart default functions.
You can do it using namespacing.
The following way is good when you have very different charts.
Default graphic:
var defaultChart = {
chartContent: null,
highchart: null,
defaults: {
chart: {
alignTicks: false,
borderColor: '#656565',
borderWidth: 1,
zoomType: 'x',
height: 400,
width: 800
},
series: []
},
// here you'll merge the defauls with the object options
init: function(options) {
this.highchart= jQuery.extend({}, this.defaults, options);
this.highchart.chart.renderTo = this.chartContent;
},
create: function() {
new Highcharts.Chart(this.highchart);
}
};
Now, if you want to make a column chart, you'll extend defaultChart
var columnChart = {
chartContent: '#yourChartContent',
options: {
// your chart options
}
};
columnChart = jQuery.extend(true, {}, defaultChart, columnChart);
// now columnChart has all defaultChart functions
// now you'll init the object with your chart options
columnChart.init(columnChart.options);
// when you want to create the chart you just call
columnChart.create();
If you have similar charts use Highcharts.setOptions
which will apply the options for all created charts after this.
// `options` will be used by all charts
Highcharts.setOptions(options);
// only data options
var chart1 = Highcharts.Chart({
chart: {
renderTo: 'container1'
},
series: []
});
var chart2 = Highcharts.Chart({
chart: {
renderTo: 'container2'
},
series: []
});
Reference
score:4
To add to @Ricardo's great answer, I have also done something very similar. In fact, I won't be wrong if i said I went a step further than this. Hence would like to share the approach.
I have created a wrapper over the highchart library. This gives multiple benefits, following being the main advantages that encouraged going in this path
- Decoupling: Decouples your code from highcharts
- Easy Upgrades: This wrapper will be the only code that will require modification in case of any breaking changes in highchart api after upgrades, or even if one decides to move to a differnt charting library altogether (even from highchart to highstock can be exhaustive if your application uses charts extensively)
- Easy of use: The wrapper api is kept very simple, only things that may vary are exposed as options (That too whose values won't be as a deep js object like HC already has, mostly 1 level deep), each having a default value. So most of the time our chart creation is very short, with the constructor taking 1
options
object with merely 4-5 properties whose defaults don't suit the chart under creation - Consistent UX: Consistent look & feel across the application. eg: tool tip format & position, colors, font family, colors, toolbar (exporting) buttons, etc
- Avoid duplication: Of course as a valid answer of the asked question it has to avoid duplication, and it does to a huge extent
Here is what the options
look like with their default values
defaults : {
chartType : "line",
startTime : 0,
interval : 1000,
chartData : [],
title : "Product Name",
navigator : true,
legends : true,
presetTimeRanges : [],
primaryToolbarButtons : true,
secondaryToolbarButtons : true,
zoomX : true,
zoomY : false,
height : null,
width : null,
panning : false,
reflow : false,
yDecimals : 2,
container : "container",
allowFullScreen : true,
credits : false,
showAll : false,
fontSize : "normal", // other option available is "small"
showBtnsInNewTab : false,
xAxisTitle : null,
yAxisTitle : null,
onLoad : null,
pointMarkers : false,
categories : []
}
As you can see, most of the times, its just chartData
that changes. Even if you need to set some property, its mainly just true/false types, nothing like the horror that highchart constructor expects (not critizing them, the amount of options they provide is just amazing from customization Point of View, but for every developer in the team to understand & master it can take some time)
So creation of chart is as simple as
var chart=new myLib.Chart({
chartData : [[1000000,1],[2000000,2],[3000000,1],[4000000,5]]
});
score:6
I know this has already been answered, but I feel that it can be taken yet further. I'm still newish to JavaScript and jQuery, so if anyone finds anything wrong, or thinks that this approach breaks guidelines or rules-of-thumb of some kind, I'd be grateful for feedback.
Building on the principles described by Ricardo Lohmann, I've created a jQuery plugin, which (in my opinion) allows Highcharts to work more seamlessly with jQuery (i.e. the way that jQuery works with other HTML objects).
I've never liked the fact that you have to supply an object ID to Highcharts before it draws the chart. So with the plug-in, I can assign the chart to the standard jQuery selector object, without having to give the containing <div>
an id
value.
(function($){
var chartType = {
myArea : {
chart: { type: 'area' },
title: { text: 'Example Line Chart' },
xAxis: { /* xAxis settings... */ },
yAxis: { /* yAxis settings... */ },
/* etc. */
series: []
},
myColumn : {
chart: { type: 'column' },
title: { text: 'Example Column Chart' },
xAxis: { /* xAxis settings... */ },
yAxis: { /* yAxis settings... */ },
/* etc. */
series: []
}
};
var methods = {
init:
function (chartName, options) {
return this.each(function(i) {
optsThis = options[i];
chartType[chartName].chart.renderTo = this;
optsHighchart = $.extend (true, {}, chartType[chartName], optsThis);
new Highcharts.Chart (optsHighchart);
});
}
};
$.fn.cbhChart = function (action,objSettings) {
if ( chartType[action] ) {
return methods.init.apply( this, arguments );
} else if ( methods[action] ) {
return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
} else if ( typeof action === 'object' || !action ) {
$.error( 'Invalid arguments to plugin: jQuery.cbhChart' );
} else {
$.error( 'Action "' + action + '" does not exist on jQuery.cbhChart' );
}
};
})(jQuery);
With this plug-in, I can now assign a chart as follows:
$('.columnChart').cbhChart('myColumn', optionsArray);
This is a simplistic example of course; for a real example, you'd have to create more complex chart-properties. But it's the principles that concern us here, and I find that this approach addresses the original question. It re-uses code, while still allowing for individual chart alterations to be applied progressively on top of each other.
In principle, it also allows you to group together multiple Ajax calls into one, pushing each graph's options and data into a single JavaScript array.
The obligatory jFiddle example is here: http://jsfiddle.net/3GYHg/1/
Criticism welcome!!
Source: stackoverflow.com
Related Query
- Manage multiple highchart charts in a single webpage
- Highchart multiple bar charts in a single webpage
- Can we manage multiple highchart charts in a single function by changing type in chart drawing functionm
- Highchart multiple axes - sync axes on multiple charts
- Highcharts multiple charts on a single page using c# asp.net mvc3
- Highchart Single Legend to control Multiple chart
- Multiple charts in separate divs, single range and zoom picker
- When adding point on dynamically created Multiple Highchart Graphs on a single page, the plot line draws to the start point instead of last point?
- How to plot multiple lines in a single graph using HighChart with JSON
- How to display Multiple Highchart in single page
- Multiple Charts on single page RAZOR MVC4
- Highstock Single Navigator for multiple Charts
- Why code of Horizonal line(y-axis) on a single in Highcharts get applied to all other charts integrated with Webdatarocks
- Hightcharts - multiple data in one single pie charts
- Highchart - adding more series to one of multiple synced highstock charts
- Multiple Pie Charts Of Variable Data With Single Legend Item Click
- Highchart Color Issue for series with single data with multiple colors
- Highchart - Angular 9: How to export all charts into single pdf?
- Draw multiple series in Highchart from single JSON data container
- Drilldown multiple levels Highchart
- Background color for multiple Highchart panes, in Vue app
- Polymer Template Repeat Over Multiple Charts
- Highcharts - multiple charts
- Multiple series in HighStock charts
- Highchart axis max with multiple axes
- Highcharts: update series on multiple charts with same data
- Highcharts: Plot multiple values in single category
- Is multiple level Highchart Drilldown possible in adjacent charts?
- Single series drilldown to multiple series Highcharts
- highchart change color of single bar in single category
More Query from same tag
- Stacked and grouped column in time series
- How to change color of line above or below specify curve line in Highcharts?
- Is it possible to show text on top of an Arearange chart
- Cannot display a legend with special character in highchart from the serie name
- Formatting tooltip for everviz
- How to add fill color in highcharts data series
- Highcharts JS: barchart select the only selected bar without the rest in series
- How to format string in Response.Write?
- Add Local HTML and JS file using React Native Webview
- Chrome won't display the x-axis labels in Highcharts, Safari and Firefox do it
- Why are there disabled buttons in HighStock Range Selector? And how to enable them?
- Using Viewmodel and datepicker with Dotnet Highchart in MVC
- Draw highcharts with many year for xAxis
- Highcharts change pointPlacement through javascript
- Highcharts converting a column chart to a pie chart
- ColorAxis in percentage bar. Approach. Highcharts
- Why doesn't highcharts solidgauge charts scale the way I expect?
- Tooltip in Scatter
- how to add values from a database output to the data field in Line Chart of Chart.js
- Link multiple chart controls in HighCharts
- Parse HTTP Response that Contains Serialized Object with Functions
- Highchart update tooltip when setData
- Date format issue in highcharts
- How to display a separating line in Highcharts exporting menu?
- Submit form data to Highcharts addPoint method to dynamically update form
- How to Get element properties from Highchart
- Highcharts display alternate x axis
- Chart Width no render ok
- Using HighCharts setData for multiple variables?
- epoch datetime not displaying correctly in HighStock chart