Chart.js V2 formatting / styling labels - javascript

So in version 1 of chart.js we could use legendTemplates to format and style where and how the labels of a chart showed up. However since switching to v2 I cannot seem to find an equivilant. See my example below of a pie chart with the labels way to condensed.
Ideally I would be able use some form option to move, spread out or otherwise style these labels.
Here is an example of the old legend template I used
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend text-center\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label.capitalizeFirstLetter()%><%}%></li><%}%></ul>"

You can configure the legend using the config options section, as explained here:
http://www.chartjs.org/docs/latest/configuration/legend.html
Example:
var chartInstance = new Chart(ctx, {
type: 'pie',
data: data,
options: {
legend: {
position: 'left',
labels: {
boxWidth: 15,
padding: 20
}
}
}
})
This code will move the legend to the left side of the chart, will make the colored boxes smaller, and will increase the amount of whitespace between the legend items.
Working JSFiddle: https://jsfiddle.net/o81qqrLn/1/
You can view a full list of configurable legend and label options is the documentation linked above.

Related

"Inline" labels in ChartJS

Is it possible to render a chart with "inline" labels between horizontal bars in ChartJS?
You can use chartjs-plugin-datalabels for this which is very useful when displaying labels on data for any type of charts and is highly customizable.
Note that this requires Chart.js 2.7.0 or later.
Use it by including it under the plugins key of your chart options as shown in the following solutions below.
Solution #1.
The configuration below will display your labels on the top center of each bar. See working example.
var options = {
plugins: {
datalabels: {
// use the formatter function to customize the labels displayed
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
},
align: "top",
anchor: "center",
offset: 25,
padding: -2,
clip: true,
font: {
size: "16",
weight: "bold"
}
}
}
};
However, this is not exactly like the screenshot you provided so,
Solution #2.
Here's one workaround I can suggest to replicate the exact behaviour that you want.
anchor: 'start' and align: -60: that will bring your data label on top, left aligned
make your chart start at zero by setting scale.ticks.beginAtZero to true
offset: 25: distance (in pixels) to pull the label away from the anchor point
padding: function() {}: use a scriptable option to dynamically compute the left padding based on the label approximate size since adding a specific padding will only work if your labels have the same width that doesn't change which is not this case
See working example for a detailed overview of the configurations.
This solution will work but it's definitely not ideal since the
position of these labels may change depending on the label size, bar
thickness, and the size of the chart.

Chart.js, adding footer to chart

Using Chart.js 2.0. I'm looking for a way to add a footer (line of text) at the bottom of the chart in order to display sources of data.
I tried to solve it via the option object, the same way as title and legend are included and modified. Like this:
`options: { ...
footer: {
display: true,
text: 'data from xy'
}
}`
I saw 'footer' several times mentioned in the documentation and ways to style it or use it in the context of 'tooltips', but haven't seen anything how to add it concretely.
EDIT/UPDATE:
I've found two workarounds (but no perfect solution) to add a footer to the chart while trying to solve this. In case someone is running into same problem like I did, here some suggestions how to solve this.
Nr. 1: adding a HTML element. This workaround has the disadvantage that the added HTML element is not shown if a user downloads the chart as a .png. Maybe this is the best solution, if the element doesn't have to be visible if a user downloads the chart as a .png.
`var myChart = new Chart(ctx, {
type: 'line',
data: { ... },
options: {
legend: { ... },
...
legendCallback: function(){
return '<p>bla bla</p>';
},
...
},
});
document.getElementById('legendID').innerHTML =
myChart.generateLegend();`
adding AFTER the canvas a div to append the new HTML element
<div id=legendID></div>
Nr. 2: adding another dataset which is empty but a label which contains the information that is supposed to be displayed. borderColor and backgroundColor set to transparent. Adding some empty labels (" ") gives some distance between labels and the footer which is added. The disadvantage of this workaround are the limited possibilities for styling.
Nr. 3: the solution of ana liza. This finally works best for my case since the added info is visible on the .png.
From the official docs:
Labeling Axes
When creating a chart, you want to tell the viewer what data they are viewing. To do this, you need to label the axis.
The scale label configuration is nested under the scale configuration in the scaleLabel key. It defines options for the scale title. Note that this only applies to cartesian axes.
You can add labels for both axes but in your case, since you only need it on the x-axis, your chart options should look similar to this.
var options = {
scales: {
xAxes: [
{
scaleLabel: {
display: true,
labelString: 'Party size',
fontColor: '#C7C7CC',
fontSize: 11
}
}
]
}
};

Increase spacing between legend and -chartartJs

I have a bar chart where I have drawn 3 vertical lines, each with it's own label at the top. I would like those labels to be above the top of the y-axis (above the 30% line in the example) but below the legend. I can't figure out how to increase the space between the top legend and the chart such that I can have my vertical line labels (15, 24 & 33) be off of the chart itself but below the legend. Any ideas?
I assume you are using chart.js. If yes, you can use custom HTML legends and apply style rules to them. Start your chart with the normal legends hidden and apply the generateLegend() method to a custom div.
var customChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
legend: {
//Because you are going to show your own legend
display: false
}
}
});
//insert legend to any div of your liking and manipulate via CSS
document.getElementById("custom-legend").innerHTML = customChart.generateLegend()
Documentation: http://www.chartjs.org/docs/latest/configuration/legend.html#html-legends
Fiddle example: https://jsfiddle.net/gmyy3rf5/

Angular-ChartJS align legend right center

I'm using the Angular-ChartJs wrapper to create a doughnut chart. I'm able to align the legend at the right top using this options:
legend: {
display: true,
position: 'right',
fullWidth:true
}
On the left image you can see how it is and on the right picture you can see how it should be. (the right image is not totally correct aligned but you get what I mean)
Is there a way to create a custom legend with the data of the chart and align that legend 'right center' to the chart?
The answer is 'options['legendCallback']'
I pass the chart options to the canvas using the element attribute 'chart-options="$ctrl.options"'
disable legend in chart options '$ctrl.options['legend']['enabled'] = false'
create your own legend using '$ctrl.options['legendCallback']'
Example:
$ctrl.options['legendCallback'] = function(chart) {
const text = []
text.push('<div class="rr-doughnut-chart-legend">')
// use dynamic legend id to handle multiple charts at once on one page
text.push('<ul class="' + chart.id + '-legend">')
// INSERT YOUR CUSTOM LEGEND HERE (perhaps generated automatically with chart object)
text.push('</ul>')
text.push('</div>')
return text.join('')
}

FLOT plot chart legend CSS being overwritten

I am experimenting with the FLOT plot tool and having some problem with the legend. Specifically, the CSS for the legend must be being overwritten somewhere in my code because the legend is looking like this:
When I try to pass legend options to the plot, they do not appear. What do I need to do fix this CSS problem? Thanks.
Here is some of the code I am working with:
var options = {
series: {
lines: { show: true },
points: { show: true },
legend: {
margin: 5
}
}
};
$.plot("#flotcontainer", [ json ], options);
The margin option from flot specifies the distance to the plot edge which seems about right at 5 pixels. Try to set the position option too (see the documentation for more information).

Categories