Hide x-axis label in chartsjs [duplicate] - javascript

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

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]

Dygraph dynamic update legend values disappear

I am using a dygraph to monitor a CSV file and use the dynamic update function. When I hover over the graph to show the values of the curves in the legend, they disappear as soon as the graph is updated, which is a bit annoying.
<html>
<head>
<script type="text/javascript" src="/static/dygraph-combined.js"></script></head>
<body>
<div id="psu"></div>
<script type="text/javascript">
g = new Dygraph(document.getElementById("psu"), "/data/psu",
{
legend: 'always',
hideOverlayOnMouseOut: false,
ylabel: 'current (A)',
height: 480,
width: 640,
sigFigs: 2,
title: 'power interface monitor',
xValueFormatter: Dygraph.dateString_,
xAxisLabelFormatter: Dygraph.dateString_,
xTicker: Dygraph.dateTicker
} );
window.intervalId = setInterval(function(){g.updateOptions( { 'file': "/data/psu" } ); }, 1000);
</script>
</html>
So the graph is all displaying correctly and the data is updated, only the legend values disappear after the graph is refreshed with g.updateOptions(). I was thinking maybe I can re-trigger some kind of "mouseover" event after g.updateOptions() so the values come back, but there might be a cleaner way of doing it.
Thanks.
I found a solution to my problem, but I am not sure how well it is implemented. I share it here so others might find it:
$(document).ready(function() {
var data = [];
var t = new Date();
for (var i = 10; i >= 0; i--) {
var x = new Date(t.getTime() - i * 1000);
data.push([x, Math.random()]);
}
var last_mousemove_evt = null;
var on_graph = false;
var g = new Dygraph(document.getElementById("div_g"), data, {
legend: 'always',
drawPoints: true,
showRoller: true,
valueRange: [0.0, 1.2],
labels: ['Time', 'Random'],
highlightCallback: function(e, x, pts, row) {
last_mousemove_evt = e;
on_graph = true
},
unhighlightCallback: function(e) {
on_graph = false;
}
});
// It sucks that these things aren't objects, and we need to store state in window.
window.intervalId = setInterval(function() {
var x = new Date(); // current time
var y = Math.random();
data.push([x, y]);
g.updateOptions({
'file': data
});
if (on_graph) {
g.mouseMove_(last_mousemove_evt);
}
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/1.1.1/dygraph-combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="div_g" style="width:600px; height:300px;"></div>
So I end up using the highlightCallback and unhighlightCallback options so I can figure out the mouse position and after a dynamic update call then the dygraph.mouseMove_() function to redraw the legend values. Seems to work.
Please let me know if there is a nicer solution around. Might be good to include this functionality in the dygraph.updateOptions() by default, as it seems weird that the legend values disappear after an update.

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

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>'
}

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.

How to color Google Column Chart's every bar differently and keep them as it is

Though I have successfully colored the bars of google chart individually but not able to keep them when we hover mouse over it. It is getting reset back to blue(which is default).
Here is the jsfiddle of what I have done jsfiddle.
I tried to control the hover behaviour with multiple ways like below.
This I am keeping outside (document.ready) but inside script tag.
1)
$('#chart_div').hover(
function() {
$('#chart_client').hide(); // chart_client is another google chart div.
}, function() { // just for testing I was doing hide/show of that.
$('#chart_client').show();
}
);
2)
$("#chart_div").on({
mouseenter: function () {
$('#chart_client').hide();
},
mouseleave:function () {
$('#chart_client').show();
}
},'rect');
3)
google.visualization.events.addListener('#chart_div', 'ready', function () {
$('#chart_div rect').mouseover(function (e) {
alert('hello');
});
});
I must be doing something wrong, could you please tell me what and where.
I solved it using below code. Earlier I was trying to create charts using dynamically adding rows into chart(please visit my jsfiddle) but with this below approach I am first preparing data(converting dynamic to static) and adding that static data in to chart's 'arrayToDataTable' method.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawUserKeywordChart);
function drawUserKeywordChart() {
var val = 'Tax:47;Finance:95;Awards:126;Bank:137;Debt:145;';
var length = val.length;
var array = [];
//preparing data
while(length>0){
var sepAt = val.indexOf(";");
var value = parseInt(val.substring(val.indexOf(":")+1, sepAt));
array.push(val.substring(0, val.indexOf(":")));
array.push(value);
val = val.substring(val.indexOf(";")+1, length);
length = val.length;
}
var data = google.visualization.arrayToDataTable([
['Keyword', 'Occurences', { role: 'style' }],
[array[0], array[1], '#8AA3B3'],
[array[2], array[3], '#A9B089'],
[array[4], array[5], '#848C49'],
[array[6], array[7], '#44464A'],
[array[8], array[9], '#704610'],
]);
var options = {
title: 'Keyword Matches',
width: 660,
height: 450,
titleTextStyle:{bold:true,fontSize:20},
legend:{position:'none'}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_keyword1'));
chart.draw(data, options);
}
Please advice if you find anything wrong here or you have better approach than this.

Categories