Chart.js setting maximum bar size of bar chart - javascript

I want to limit the maximum width of a bar chart
My CODE:
<script>
// bar chart data
var a=[];
a.push('kalai 2015-04-11');
var b=[];
b.push('300');
var barData = {
labels : a,
datasets : [
{
fillColor : "#48A497",
strokeColor : "#48A4D1",
data : b
}
]
}
// get bar chart canvas
var income = document.getElementById("income").getContext("2d");
// draw bar chart
new Chart(income).Bar(barData, {scaleGridLineWidth : 1});
<!--new Chart(income).Bar(barData);-->
</script>
What is the way to do so
It looks like this for single value
The size of the bar reduces as the number of bar increases How can i set maximum bar size to make it more viewable

You can add new options, which are not available by default.But you need to edit chart.js
In Chart.js add these lines of code
Step 1:
//Boolean - Whether barwidth should be fixed
isFixedWidth:false,
//Number - Pixel width of the bar
barWidth:20,
Add these two line in defaultConfig of Bar Chart
Step 2:
calculateBarWidth : function(datasetCount){
**if(options.isFixedWidth){
return options.barWidth;
}else{**
//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
return (baseWidth / datasetCount);
}
Add this condition in calculateBarWidth function of barchart
Now you can set barWidth in custom js file as option by setting
isFixedWidth:true,
barWidth:xx
If you don't want to specify fixed barwidth, just change isFixedWidth:false

Its kinda late to answer this but hope this helps someone out there... play around with barDatasetSpacing [ adds spacing after each bar ] and barValueSpacing [ adds spacing before each bar ] to be able to achieve your desired bar width.. example below when initiating your bar chart
... barDatasetSpacing:10, barValueSpacing:30, ...
Hope it helps..

I did it by extending Bar chart, and calculating barValueSpacing dynamically. I use angular chartjs
var MAX_BAR_WIDTH = 50;
Chart.types.Bar.extend({
name: "BarAlt",
draw: function(){
var datasetSize = n // calculate ur dataset size here
var barW = this.chart.width / datasetSize;
if(barW > MAX_BAR_WIDTH){
this.options.barValueSpacing = Math.floor((this.chart.width - (MAX_BAR_WIDTH * datasetSize)) / datasetSize);
}
Chart.types.Bar.prototype.draw.apply(this, arguments);
}
});

Did you tried following options?
{
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
}

Related

How to display percentages in pie chart (ChartJS)

I am in the development of some graphs with the help of the Chart.js library and among them I am making use of a pie chart or better known with Pie Chart and I am looking for some way to add their respective percentages on the graph as well as the image that I add as an example at the end of the snippet.
Currently the graph is shown but I cannot show their respective percentages.
const pieData = [
{
value: 72,
color: "#4EADEB",
// highlight: "#FF5A5E",
label: "Avance"
},
{
value: 28,
color: "#3F86CB",
//highlight: "#5AD3D1",
label: "Pendiente"
}
];
const pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 0, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//String - A legend template
legendTemplate:
'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
};
const pieCtx = document.getElementById("myPieGraph").getContext("2d");
const myPieChart = new Chart(pieCtx).Pie(pieData, pieOptions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js"></script>
<canvas id="myPieGraph" height="120" width="240"></canvas>
Example Image:
Note:
Before the question closes for possible duplication, in this question it seeks to add the percentages but the version they use here is 0.4.0, the version that I am using of ChartJS is 1.1.1.
The use of its properties are different.

keep fixed size of the bars in Highcharts

I want to maintain the same size of the bars. no matter how many there are values.
here is the size I want to have all bars.
when added four values the bars become smaller.
I want all the bars are the same size. no matter that I have to scroll to see the other bars (this is what I want).
this is my code:
http://jsfiddle.net/Laxfsbtb/
$('#container').highcharts({
chart: {
type: 'bar'
},
series: [{
name: 'text1',
data: [1000, 950,920,880,850,234],
color: "#FF0000"
}, {
name: 'text2',
data: [800,770,750,740,730,4324],
color: "#000000"
}, {
name: 'text3',
data: [600,540,535,500,400,324],
color: "#00FF00"
}]
});
});
This can be done with the pointWidth parameter like:
plotOptions: {
series: {
pointWidth: 20 //width of the bar/column/point.
}
},
To allow scrollbar you should probably upgrade to highstock but that only works horizontally. Or you could set up a div that allows the chart to be "larger" on the inside and scroll through that div window.
Not sure precisely what you're looking for, but this might help.
I put together an example a while ago to adjust the height of the chart according to the number of bars, using some preset parameters:
var barCount = chartData.length;
var pointWidth = 20;
var marginTop = 60;
var marginRight = 10;
var marginBottom = 50;
var marginLeft = 100;
var pointPadding = 0.3;
var chartHeight = marginTop
+ marginBottom
+ ((pointWidth * barCount) * (1 + groupPadding + pointPadding));
So, tell it what size you want the bars, how much padding between them, how much margin at top and bottom of chart, and how many data points you have.
Bars will stay the same size and spacing while the chart itself grows to accommodate them.
example:
http://jsfiddle.net/jlbriggs/kpu5d1qf/
To see it work, change the 12 in this line:
var chartData = randomData(12, true);
To whatever number you want.
((Edit
Since you are working with grouped data, you'll have to change the math a little bit.you'll need to account for the number of groups, and multiply hat by the groupPadding, added to the number of points * the pointPadding.
You'll also have to make getting your count of data points slightly more complex.

jQuery Flot Charts: Auto bar width with dynamic items

My charts output dynamic data based on input filters. These can have 1 to 30 bars and they resize on screen resize/device. Just an example, currently where there's < 5 bars and the charts width is 1138px (max), then I have pretty big bars in width.
Q. How is this problem dealth with?
var options = {
xaxis: { ticks: ticks},
grid: { clickable: false, hoverable: true },
series: { stack: true, bars: {show: true,align: 'center',barWidth: 0.5,lineWidth: 2,fillColor: {colors: [{opacity: 0.9}, {opacity: 0.9}]}} },
legend: {container: ".widget-legend"}
};
Assuming you want to give your bars the same pixel width whether there are 1 or 30 bars, you can calculate the value for barWidth from the width of the chart (in x axis units and pixels, correcting for axes and margins) using cross-multiplication. A reasonable pixel width for up to 30 bars on 1100 pixels would be around 20 pixels per bar.
var chartWidthInPixels = 1100 * 0.95; // or $('#chart').width() * 0.95
var barWidthInPixels = 20; // or chartWidthInPixels / 50
var chartWidthInAxisUnits = (max(ticks) - min(ticks)) + 1; // this will be 1 for one bar
var barWidthInAxisUnits = barWidthInPixels * (chartWidthInAxisUnits / chartWidthInPixels);
For one bar with the above example values this gives around 0.019 for the barWidth. By variation of the constants in the formulas you can modify the calculation.

Chart.js not appearing in tabs

I know there are examples but they didn't work for me.
I'm using joomla and trying to embed a line chart in a tab, works on the first tab but not the 2nd, any ideas would be appreciated.
here's the script and I don't really know javascript that well.
Many Thanks:
<canvas id="myChart-a" height="320" width="1200"></canvas>
<script src="templates/jux_forlio/js/chart.js"></script>
<script type="text/javascript">
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
fillColor : "rgba(162,29,9,0.5)",
strokeColor : "rgba(162,29,9,1)",
pointColor : "rgba(162,29,9,1)",
pointStrokeColor : "#fff",
data : [30,29,26,23,19,16,15,17,19,22,25,28]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [20,19,17,14,10,8,7,9,10,13,16,18]
}
]
},
options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : true,
scaleShowValues : true,
//Boolean - If we want to override with a hard coded scale
scaleOverride : false,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,
//String - Colour of the scale line
scaleLineColor : "rgba(f,f,f,.1)",
//Number - Pixel width of the scale line
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
scaleShowLabels : true,
//Interpolated JS string - can access value
scaleLabel : "<%=value%>",
//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",
//Number - Scale label font size in pixels
scaleFontSize : 20,
//String - Scale label font weight style
scaleFontStyle : "normal",
//String - Scale label font colour
scaleFontColor : "#fff",
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 3,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//Boolean - Whether to animate the chart
animation : true,
//Number - Number of animation steps
animationSteps : 60,
//String - Animation easing effect
animationEasing : "easeOutQuart",
//Function - Fires when the animation is complete
onAnimationComplete : null,
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true
}
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart-a").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineChartData, options);
</script>
Assuming the tabs HTML includes "li" tags - like this -
<li class="" onclick="javascript:drawChart();"> </li>
Note: on clicking a javascript function is called. Add onclick attribute for the tab-li where you want to show the chart.
Then the remaining code remains the same except the lines given below moved inside the JS function .
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart-a").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineChartData, options);
This should do the trick!
<script>
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
fillColor : "rgba(162,29,9,0.5)",
strokeColor : "rgba(162,29,9,1)",
pointColor : "rgba(162,29,9,1)",
pointStrokeColor : "#fff",
data : [30,29,26,23,19,16,15,17,19,22,25,28]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [20,19,17,14,10,8,7,9,10,13,16,18]
}
]
},
options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : true,
scaleShowValues : true,
//Boolean - If we want to override with a hard coded scale
scaleOverride : false,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,
//String - Colour of the scale line
scaleLineColor : "rgba(f,f,f,.1)",
//Number - Pixel width of the scale line
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
scaleShowLabels : true,
//Interpolated JS string - can access value
scaleLabel : "<%=value%>",
//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",
//Number - Scale label font size in pixels
scaleFontSize : 20,
//String - Scale label font weight style
scaleFontStyle : "normal",
//String - Scale label font colour
scaleFontColor : "#fff",
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 3,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//Boolean - Whether to animate the chart
animation : true,
//Number - Number of animation steps
animationSteps : 60,
//String - Animation easing effect
animationEasing : "easeOutQuart",
//Function - Fires when the animation is complete
onAnimationComplete : null,
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true
}
function drawChart()
{
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart-a").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineChartData, options);
}
</script>
I hope this helps!

How do I add column-specific plotlines using High Charts?

I am trying to make a column chart using js HighCharts that has 2 unique plotlines for each column of the chart, rather than a single plotline that spans the width of the entire chart.
This way I will be able to show a max and min value for EACH column.
You can't make an actual plot line that works that way.
You can use a scatter series, and define a custom line marker type, like here:
http://jsfiddle.net/highcharts/e96yX/
example code for both a horizontal line and a vertical line:
Highcharts.Renderer.prototype.symbols.vline = function(x, y, width, height) {
return ['M',x ,y + width / 2,'L',x+height,y + width / 2];
};
Highcharts.Renderer.prototype.symbols.hline = function(x, y, width, height) {
return ['M',x ,y + height / 2,'L',x+width,y + width / 2];
};
alternatively, based on your question, a column range chart may be helpful as well:
http://highcharts.com/demo/columnrange

Categories

Resources