Chart.js - 2 datasets in line chart always show tooltips? - javascript

How to always show tooltip BUT with 2 datasets for line chart?
Here is jsfiddle which works with one dataset.
My tooltip code is:
var options =
{
tooltipTemplate: "<%= value %>",
showTooltips: true,
onAnimationComplete: function()
{
this.showTooltip(this.datasets[0].points, true);
},
tooltipEvents: []
}
And in same appirience I would like to have with 2,3 or more datasets.
Here is jsfiidle where I tried 2 datasets.
I guess, this line has something to do with it:
this.showTooltip(this.datasets[0].points, true);

I manage to find a solution. Here it is: Chart JS: Always show tooltips in a multi dataset line chart
But if you want to do the same thing but on Bar chart, you need to change:
for (var dataIndex = 0; dataIndex < this.datasets[0].points.length; dataIndex++) {
to
for (var dataIndex = 0; dataIndex < this.datasets[0].bars.length; dataIndex++) {
and from
dataCollection = dataset.points;
to
dataCollection = dataset.bars;
At the bottom you should call Bar chart, eg.
var chart = new Chart(ctx).Bar(dataBar, options);

Try this:
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
}

Related

ChartJS different border color for legend

I need to set a different border color for the legend than the actual chart; whenever I add border color to the chart data, it gets applied to both legend and chart. And I couldn't find any options for setting different border colors for the legend in documentation
Here's a screenshot of what I'm trying to achieve, any idea?:
The only way I have found to do this and some other customisation on the legend is to implement the legend item interface.
The accepted answer here in combination with the legend item interface should be a good start.
Here's a jsfiddle that I made from that answer, but updated for chartjs 3.7.1. The main part to focus on is this:
options: {
plugins: {
legend: {
labels: {
usePointStyle: true,
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
return {
text: label,
fillStyle: ds.backgroundColor[i],
strokeStyle: ds.legendOutline[i],
lineWidth: ds.borderWidth,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
index: i
};
});
} else {
return [];
}
}
}
}
}
strokeStyle is the outline property, and I've made a field in the dataset called legendOutline. legendOutline and the data from the dataset are both referenced with i, so the legendOutline[i] points to the label representing data[i]

How to plot area type highchart?

Here is the jsfiddle Code reproduction,
I am using Highcharts to plot an area graph, how do I do the below ?
I need to move the y-axis labels to the right
Plot Area chart of 3 colors ['#762232', '#EFCA32', '#007788'] with their respective values.
Expected Output
Set yAxis.opposite to true.
Add two more series and use tickPositioner to show thier last values as labels.
yAxis: {
opposite: true,
showFirstLabel: false,
showLastLabel: false,
tickPositioner: function() {
var prevTickPos = this.tickPositions,
tickPositions = [prevTickPos[0], prevTickPos[prevTickPos.length - 1]],
series = this.chart.series;
series.forEach(function(s) {
tickPositions.push(s.processedYData[s.processedYData.length - 1]);
});
tickPositions.sort(function(a, b) {
return a - b;
});
return tickPositions;
},
...
}
Live demo: https://jsfiddle.net/BlackLabel/gk1t6cp2/
API Refernce: https://api.highcharts.com/highcharts/yAxis.opposite

ChartJS tooltip to always show on graph (for mode "label/index")

I have a stacked bar chart and I want to always display the tooltip on my stacked bar. I manage to get it to work but the result is not what I want. It displayed the tooltip for each stacked bar separately; what I want is to show the tooltip for both the stacked bar in one / grouped.
By using tooltip option mode: 'label' or 'index', it works but only work on hover (mouse over). I want to display the grouped tooltip always on the graph.
Below the code that I am currently using:
In plugin service register, below was added to always show the tooltip on the graph:
Chart.pluginService.register({
beforeRender: function(chart) {
//chart.options.tooltips.mode = 'index';
var datasets = chart.data.datasets;
chart.pluginTooltips = [];
for (i = 0; i < datasets.length; i++) {
for (j = 0; j < datasets[i].data.length; j++) {
if (Number(datasets[i].data[j]) > 0) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [chart.getDatasetMeta(i).data[j]]
}, chart));
}
}
}
}, // end beforeRender
afterDatasetsDraw: function(chart, easing) {
// Draw tooltips
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
} // end afterDatasetsDraw
});
In the chart option, below tooltip option was added:
*tooltip with label mode was to show the tooltip as a group; this only works on hover, I want to get it to work to always display on the graph.
tooltips: {
mode: 'label',
Below the result that I currently get:
Below the expected result that I want to have (it only shows on hover now):
My question is: How can I draw the grouped tooltip (as shown above) to display always (fixed) on the graph.

Hide x-axis label in chartsjs [duplicate]

I want to hide labels on x-axis as i have a solution to set
$scope.labels = ['', '', '', '', '', '', ''];
but in that case labels are also getting hidden on tooltip. What i want is to show labels on bars hover but i don't want to show those labels on x-axis. As it also disturbs my UX as well because charts width is too low.
I did spend too much time on this but couldn't find a solution to get rid of x-axis labels. Please help me here....
I think that's something you can do it with options setting in the latest versions of chartjs:
options: {
scales: {
xAxes: [
{
ticks: {
display: false
}
}
];
}
}
You can extend the chart to do this, like so
Chart.types.Bar.extend({
name: "BarAlt",
initialize: function(data){
Chart.types.Bar.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels;
for (var i = 0; i < xLabels.length; i++)
xLabels[i] = '';
}
});
and call it like so
var myBarChart = new Chart(ctx).BarAlt(data);
Fiddle - http://jsfiddle.net/kq3utvnu/
Thanks #Samuele for pointing this out! For really long labels, you'll need to set the labels to something shorter and then set it back to the original ones (in the chart elements) so that no space is taken up below the x axis for the labels.
Chart.types.Bar.extend({
name: "BarAlt",
initialize: function(data){
var originalLabels = data.labels;
data.labels = data.labels.map(function() { return '' });
Chart.types.Bar.prototype.initialize.apply(this, arguments);
this.datasets[0].bars.forEach(function(bar, i) {
bar.label = originalLabels[i];
});
var xLabels = this.scale.xLabels;
for (var i = 0; i < xLabels.length; i++)
xLabels[i] = '';
}
});
Fiddle - http://jsfiddle.net/nkbevuoe/
I was able to hide labels on the x-axis, while keeping the title in the tooltip by doing the following:
In chart data: labels: [""]
In chart options, add object.label = "ToolTipTitle"; before the line specifying the values that should be returned

Bar chart looks bad before change data

Hi here I set the data to the bar chart:
setDatosBarra: function(data){ //
var self = this;
var horaEstim = 0;
var horaReal = 0;
var horaTotal = 0;
if(data[0].horas_estim != '-'){
horaEstim = data[0].horas_estim;
}
if(data[0].horas_real != '-'){
horaReal = data[0].horas_real;
}
if(data[0].total_horas != '-'){
horaTotal = data[0].total_horas;
}
var datosBarra =[{data: [[0,horaEstim]], color: "#691717"}, {data: [[1,horaReal]], color: "#173D69"},{data: [[2,horaTotal]], color: "#176469"}];
self.flotLinea(datosBarra);
},
When all is ready I send the data to self.flotBar;
This is the flotBar function:
flotBar: function(datos){
var self = this;
if(datos == 0){
var data = [["SIN REGISTROS",0]];
}else{
var data = datos;
}
function getTooltip(label, x, y) {
return "<strong style='font-size:18px;'> " + y + " </strong> horas";
}
var plot = $.plot("#placeholder",data, {
series: {
bars: {
show: true,
barWidth: 0.3,
align: "center",
lineWidth: 0,
fill:.75
}
},
xaxis: {
ticks: [[0,"Horas estimadas"],[1,"Horas reales"],[2,"Total horas"]],
mode: "categories",
tickLength: 0
},
grid: {
hoverable: true,
clickable: true
},
tooltip: true,
tooltipOpts : {
content : getTooltip,
defaultTheme : false
},
});
},
Ok , and this is my problem, example:
I select a option in an dropDown:
And the bar chart looks like this:
If I select other option in the dropDown:
The bar chart looks like this:
And if I select again the first option "Correcion de errores", the bar chart looks like this:
So.. always the first time that I show the bar chart looks like in the first image , with the numbers in the line, but If I select other option looks good.
I need see good the bar chart always and no just when I select other option.
I'm using flot javascript library.
How can I fix this? sorry by my english
The main issue with the question as stated is that we do not have all the code. In essence, you should either provide all the code, or shrink down the problem to something that shows the issue and then, well, provide all the code. As far as I can guess, you have some other code somewhere else that is drawing the initial chart. The second and subsequent times? Drawn properly. To support my assertion, notice that in your initial image the captions for the x-axis tick markers (ditto the bars themselves) are right aligned not centered.
For fun, I wrote a quick jsFiddle that showed how to switch datasets using a button (much as you want to do with the drop-down) and redraw the chart:
drawChart = function(index) {
var chartData = getDataForChart(rawData[index]);
if (chart) {
chart.setData(chartData);
chart.draw();
}
else {
chart = $.plot("#barchart", chartData, chartOptions);
}
},
switchDataset = function() {
datasetIndex = (datasetIndex + 1) % datasetCount;
drawChart(datasetIndex);
};
$("#switchButton").on("click", switchDataset);
Because I decided to load new data into the chart rather than redraw it all from scratch (to be honest I saw no real difference either way), it meant that I had to pre-calculate the maximum value for the y-axis:
calcValueMax = function() {
var max = 0;
rawData.forEach(function(values) {
values.forEach(function(value) {
if (value > max) {
max = value;
}
});
});
return max;
},
// other code
chartOptions.yaxis.max = calcValueMax();
Hope that helps.

Categories