Forum Discussion

harikm007's avatar
harikm007
Data Warehouse
09-27-2024

Adding a Dropdown to Change Date Granularity in Charts

Adjusting the date granularity in charts is crucial for effective data analysis. Users often want to switch between yearly, quarterly, or monthly views to identify trends, analyze seasonal performance, or evaluate specific campaigns.

This straightforward widget script lets users toggle between year, quarter, and month views effortlessly, enhancing interactivity and simplifying data exploration.

 

widget.on('processresult', function ( se, ev ) {
    	ev.result.chart.spacing = [20, 20, 77, 20 ]
    });
	
	widget.on("domready", function(se){
	    
    	const chart = widget.chart[0][Object.keys(widget.chart[0])[0]].hc;
    	const chartContainer = prism.activeWidget ? $('.highcharts-container') : $(`widget[widgetid=${widget.oid}] .highcharts-container`);
    
    	//Time period dropdown
    	const timePeriods = {
    	                        'Weekly': 'weeks',
    					        'Monthly': 'months',
    					        'Quarterly': 'quarters',
    					        'Yearly': 'years'
    	                    };
    	
    	let ddTimePeriodId = `select-timeperiod-${widget.oid}`;
    	let dropdownHTMLTimePeriods = `<select name="select" id="${ddTimePeriodId}"></select>`;
    	
    	if($(`#${ddTimePeriodId}`).length)
    	{
    		$(`#${ddTimePeriodId}`).remove();
    	}
    	
    	chartContainer.before(dropdownHTMLTimePeriods);
    	
    	for(let key in timePeriods){
    		
    		$(`#${ddTimePeriodId}`).append(`<option value="${key}">${key}</option>`);
    		
    	}
    	
    	document.getElementById(`${ddTimePeriodId}`).value = Object.keys(timePeriods).find(key => timePeriods[key] == widget.metadata.panels[0].items[0].jaql.level);
    	var select = document.getElementById(`${ddTimePeriodId}`);
    
    	select.addEventListener('change', (e) => {
    		
    	  let selectedItem= e.target.value;
    
    	  widget.metadata.panels[0].items[0].jaql.level = timePeriods[selectedItem];
    
    	  widget.refresh();
    
    	});
	});

Check out this post to find the script for adding an attractive dropdown.
https://www.binextlevel.com/post/adding-a-dropdown-to-change-date-granularity-in-charts 

If you're looking to tackle the challenges of widget customization and simplify your script management, be sure to check out this blog post. It provides valuable insights and practical tips to help you manage and maintain your scripts more easily, leading to a smoother workflow in your data visualizations.

 

 

1 Reply

  • is there a way to make this work for pivot tables? i.e the columns are months, but we might want to collapse it to be Quarters