Tag Archives: js charts

Legends in Morris Chart

With help from this article https://github.com/morrisjs/morris.js/issues/346

This is about adding Legends to Morris charts. Though Morris chart shows legend on hovering on the graphs, but I wanted to show a legend permanently on one corner of the chart area.

Below are the codes. It is mostly plug and play code

The div in which the chart will be displayed

<div class="box-body chart-responsive">
    <div id="visitor_legend" class="bar-chart-legend"></div> <!-- the legend area -->
    <div class="chart" id="bar-chart" style="height: 300px;"></div> <!-- the chart area -->
</div>

The CSS

<style>
.bar-chart-legend {
	display: inline-block;
	right: 25px;
	position: absolute;
	top: 8px;
	font-size: 10px;
}

.bar-chart-legend .legend-item {
	display: block;
}

.bar-chart-legend .legend-color {
	width: 12px;
	height: 12px;
	margin: 3px 5px;
	display: inline-block;
}
</style>

The JS code

// Legend for Bar chart
bar.options.labels.forEach(function(label, i) {
	var legendItem = $('<span class="legend-item"></span>').text( label).prepend('<span class="legend-color">&nbsp;</span>');
	legendItem.find('span').css('backgroundColor', bar.options.barColors[i]);
	$('#visitor_legend').append(legendItem) // ID pf the legend div declared above
});

Morris charts documentation https://morrisjs.github.io/morris.js/lines.html