I am using angular-chart.js
<div class="container" ng-controller="LineCtrl">
<canvas id="bar" class="chart chart-bar" data="barChartData" options="options" series="lineChartSeries"
colours="colours" legend="true" labels="barChartLabel"></canvas>
</div>
css for this chart is
.chart #bar {
width: 100%!important;
height: 300px;
}
but chart is showing with overlapping labels like
That's because Chart.js shows all x axis labels and doesn't drop them if the overlap. There is a feature request out there for this https://github.com/nnnick/Chart.js/pull/897 - which is still open.
There is also a separate branch - https://github.com/nnnick/Chart.js/pull/521 which solves the issue. But, it hasn't been integrated into the main branch yet and you might want to read the full thread before opting for this.
There is a workaround however. You can just opt to set everything except every nth label when you pass in the labels array, like this
labels: ["Jan 1", "Jan 2",... and lots of days ....].map(function (e, index) {
return index % 5 ? "" : e;
})
Adjust the value 5 as needed. The best way would be to adjust this based on the size of the array to get x number of points or less if the number of points crosses a threshold. e.g. if you want no more than 10 points, replace 5 with size of array / 10 IF size of array > 200 or at whichever point the overlaps start. Just make sure you don't end up with too less markers :-). For instance, if you pick 30 instead of 200 as the threshold, there will be times when you have only 3 markers for 30+ data points. Or you can choose to be more creative with your mapping function (for example, make sure that you have a label at the end of the scale, etc.)
Here is an example with just Chart.js. The same logic will work with angular-chart.js as well.
var myLabels = []
var myValues = []
for (var i = 0; i < 1000; i++) {
myLabels.push("label" + i);
myValues.push(Math.random() * 1000)
}
var data1 = {
labels: myLabels,
datasets: [{
label: "My Dataset",
fillColor: "rgba(244, 6, 6, 1)",
data: myValues
}]
};
var ctx = document.getElementById("chart1").getContext("2d");
window.weeksChart = new Chart(ctx).Bar(data1, {
barShowStroke : false
});
var data2 = {
labels: myLabels.map(function (e, index) {
return index % 30 ? "" : e;
}),
datasets: [{
label: "My Dataset",
fillColor: "rgba(244, 6, 6, 1)",
data: myValues
}]
};
var ctx = document.getElementById("chart2").getContext("2d");
window.weeksChart = new Chart(ctx).Bar(data2, {
barShowStroke : false
});
with HTML
<canvas id="chart1" width="651" height="335"></canvas>
<canvas id="chart2" width="651" height="335"></canvas>
And here is the corresponding fiddle - http://jsfiddle.net/2kvwndtq/
The downside is that if you want tooltips you have to override your tooltip function as well to show the spaces with the corresponding label and not blank.
Related
I'm looking to hide the null label from my chart here. I'm working in Actuate/Opentext designer. I originally needed for there to always be 28 column slots but there isn't always data points for each of those days. If there isn't- the label on the x-axis is showing up as null. I'd like to hide this label but can't figure out how. Even changing the color of it to white but I can't get around how to manipulate this label to never show when null. Here is an image of what I'm trying to remove from my chart and the current code
beforeGeneration: function(options) { options.xAxis.max = 27
//You can change options here.
options.plotOptions = {
series: {
pointWidth: 25, //size of column
pointPadding: 0.25, //size of padding between each bar
groupPadding: 0 //padding between each value groups in x axis
}
};
},
Use formatter function:
xAxis: {
...,
labels: {
formatter: function(){
return this.value || '';
}
}
}
API Reference: https://api.highcharts.com/highcharts/xAxis.labels.formatter
I'm using Chart.js v1.0.1-beta.3. I'm creating an interactive bar chart where users can click on a bar to increase the value of that bar.
By default, the histogram begins with empty values. The y-axis in that case defaults to a [0,1] scale. When users start adding data to the histogram, the y-axis maximum changes to adjust, which causes a jarring shift in the appearance of the graph at low values.
I'd like to have the y-axis default to, say, a [0,10] scale even when no data is entered. This StackOverflow question is the most relevant info I can find on how to address problems like this; the best solution on that page is to use the 'suggestedMax' parameter in the chart options:
scales: {
yAxes: [{
ticks: {
suggestedMax : 10
}
}]
},
although this might apply only to v2+ of the library, it's hard to tell. In any event, this doesn't work, and the y-axis defaults to [1,0] when there's no data. I've also tried every combination of every other suggestion on that page, including
using scaleOverride : true, display : true, setting explicit min and max parameters within 'ticks', scaleBeginsAtZero : true, beginAtZero : true, and scaleStartValue : 0,
If I try to upgrade to the most current release, v2.7.3, the charts don't appear on the rendered page at all. I don't have the time or inclination to debug what's happening there, so I'm stuck with v1.0.1.
How do I have a bar chart default to a suggested maximum in this version? Is it even possible?
Looking through the documentation included with v1.0.1 (zip file), there doesn't appear to be a way to do this. I can't see any option to set the scale values.
In v2.7.3 this is quite simple. A working example is below. The chart starts empty, with a y-axis scale from 0-10. Clicking 'Add Series' adds a new bar with a value of 5. Clicking a bar increments value by 1.
let btn1 = document.getElementById('add'),
canvas = document.getElementById('chart'),
chart = new Chart(canvas, {
type: 'bar',
data: {
labels: [],
datasets: []
},
options: {
scales: {
yAxes: [{
ticks: {
min: 0,
suggestedMax: 10
}
}]
}
}
});
canvas.addEventListener('click', function(e) {
let idx = chart.getDatasetAtEvent(e)[0]._datasetIndex;
chart.config.data.datasets[idx].data[0]++;
chart.update();
});
btn1.addEventListener('click', function() {
chart.config.data.datasets.push({
data: [5]
});
chart.update();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<button id="add">Add Series</button> Click a bar to increment its value by 1.
<canvas id="chart"></canvas>
I found that I can create nice scatter plot with CanvasJS into my HTML templates (see the link: http://canvasjs.com/docs/charts/chart-types/html5-scatter-chart/)
I am creating a website using Django and a MySQL database.
In one of my tables (models) I have 3 fields VARCHAR containing different values:
- the 1st field contains values for X axis.
- The 2nd field contains values for Y axis.
- The 3rd field contains one letter labels.
Here is an example for one entry if it is not clear:
1st field:
999.99;-89.01;-60.29;-145.83;-140.76;-148.24;-88.70;56.92;69.08;-121.37
2nd field:
143.12;146.51;143.73;177.58;121.68;116.45;-14.05;20.77;15.82;168.20
3rd field:
CPPEEECTTE
As you can see, values are separated by ";" in fields 1 and 2.
there are 10 values in field 1, 10 values in field 2, and 10 corresponding letter labels.
All fields are 1 long string.
So my question is simple, I don't know how to make a for loop in javascript so that those coordinates will be taken in the scatter chart.
Here is the example of the canvasjs for scatter chart I want to obtain:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Title of my scatter chart"
},
data: [
{
type: "scatter",
dataPoints: [
{ x: 999.99, y: 143.12 },
{ x: -89.01, y: 146.51 },
{ x: -60.29, y: 143.73 },
{ x: -145.83, y: 177.58 },
{ x: -140.76, y: 121.68 },
{ x: -148.24, y: 116.45 }
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
All I want is to generate coordinates in dataPoints with a for loop.
The 3 fields will be 3 rows in a HTML table.
The 3rd field will be used to associate a color to a letter. (Example: C = blue, P = green, E = yellow, T = red).
I have absolutely no idea how to make that in javascript.
If someone is experienced in JS, I would really appreciate some help.
You can do so by traversing the arrays(of x,y values and color) and converting them to the format required by CanvasJS and then updating the chart options.
for(var i = 0; i < xVal.length; i++) {
chart.options.data[0].dataPoints.push({
x: parseFloat(xVal[i]),
y: parseFloat(yVal[i]),
color: colorArr[i]
});
}
Here's a jsfiddle for the same.
I'm working with highcharts and aiming to make a chart similar to this:
Now I've been playing around with the whole ordeal for a while now and I've come been able to reach the following point: http://jsfiddle.net/ccjSy/24/
$(function () {
$(document).ready(function () {
var chart = null;
var categories = ['Body Fat', 'Lean Mass'],
name = 'Body Fat vs. Lean Mass',
data = [{
y: 69,
color: '#F0CE0C',
drilldown: {
name: 'Body Fat',
color: '#F0CE0C'
}
}, {
y: 207,
color: '#23A303',
drilldown: {
name: 'Lean Mass' ,
color: '#23A303'
}
}];
// Build the data array
var browserData = [];
for (var i = 0; i < data.length; i++) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
}
// Create the chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'donutchart',
type: 'pie',
spacingTop: 0
},
title: {
text: 'Your Body Fat vs Lean Mass',
style: {"color": '#7d7d7d'}
},
series: [{
name: 'Weight',
data: browserData,
dataLabels: {
style: {
fontFamily: 'ArialMT',
fontSize: '15px',
fontWeight: 'bold',
color: '#7d7d7d'
}
},
innerSize: '70%'
}],
tooltip: {
valueSuffix: ' lbs'
},
plotOptions: {
series: {
cursor: 'pointer'
}
}
});
});
});
I am thinking of leaving the space empty in the donut chart and inserting a custom circle with the Weight labeling.
However, I'm not certain how to tackle the following problems:
1) Leave more defined white spaces in between my two columns
2) How to properly align my two data labels? (As you can see in the model, they are in a straight line with neutral lines attached)
3) How to display the data underneath the two labels with both, the pounds and the percentage, as shown in the image.
Answering each of your three questions:
"More white space between columns?" -- add a plotOptions.pie.borderWidth element. The default value is 1. I used 5 to give it more white space.
"Properly align the two data labels?" -- You can compute a custom startAngle based on the two data values which will give you the correct angle to start with. Since you only have two data values in the series, that's easy.
Calculate startAngle for pie chart
var startAngle = 0 - (90 + (180 * (data[0].y / (data[0].y + data[1].y))));
Notice that if you change the y value for the first data object, the "Body Fat" portion of the pie chart will still maintain it's correct position, even as the portion of the chart grows larger or smaller.
"Display data underneath the two labels with custom formatting?" -- use plotOptions.pie.format to apply custom formatting to the pie value labels.
format: '<div style="position: relative; top: -20px; text-align: center">{point.name}<br><b><span style="font-size: 29px">{point.percentage:.0f}%</span></b> ({point.y} lbs)</div>'
Here's a working JSFiddle to see the results. You'll still need to add a dark gray circle behind the pie chart and add the "Total Weight" text but that shouldn't be too difficult.
Since I'm sure you'll be wondering about this, I should mention that there's a lot of white space under the pie chart title because it's leaving enough room for other labels that may appear above or below the pie. Since you're only using two values that will always be on the left/right sides of the pie chart, that doesn't change the fact that HighCharts is preparing to have other labels that may need to be displayed in the surrounding area.
I am using Jquery Flot to create a pie chart based on three different values, pause, nopause and sleeping. Initially it draws th pie chart correctly but after some redraw it gives me the following error.
Could not draw pie with labels contained inside canvas
My code is
Lecturer.socket.onmessage = function (message) {
var str = message.data;
var msg = str.split(":");
if(msg[0] == 'pause'){
var pause = parseInt(msg[1]);
var noPause = parseInt(msg[2]);
var sleeping = parseInt(msg[3]);
var data = [
{label: "Pause", data:pause},
{label: "No Pause", data:noPause},
{label: "Sleeping", data:sleeping}
];
var options = {
series: {
pie: {show: true}
},
legend: {
show: false
}
};
$.plot($("#pie-placeholder"), data, options);
}
};
HTML is
<div id="live-placeholder" class="flot"></div>
All the require js libraries are included. What I m doing wrong? Any Help ?
Thanks
You've got two problems:
1.) your placeholder div id doesn't match the $.plot call. live-placeholder != pie-placeholder.
2.) You don't need to calculate the percents yourself. Flot will do it internally.
See a working fiddle here.