Chart not obeying width and height attributes - javascript

My Morris JS chart is not rendering well inside a bootstrap column, like the documentation tells I gave width and height attributes to the container but the chart is not obeying them.
Does someone have a clue to fix it?
var graficoCampanhaefbe = Morris.Bar({
element: 'graficoCampanhaefbe',
data: [{"nome": "Redes Sociais 1459", "destinatarios": "2", "abertos": "4", "clicados": "2", "capturados": "3"}],
barColors: ['#00A5DB','#6EA700','#FFB203','#B50000'],
xkey: 'nome',
ykeys: ['destinatarios','abertos', 'clicados', 'capturados'],
labels: ['Destinatario','Abertos', 'Clicados', 'Capturados'],
hideHover: 'always'
});
When I set resize: true and resize the window the graphic renders just perfect.

In your $(document).ready, try to trigger a window resize after you initialized your Morris Bar and set your resize Morris Bar parameter to true:
$(document).ready(function () {
var graficoCampanhaefbe = Morris.Bar({...});
//graficoCampanhaefbe.redraw(); //if needed
$(window).trigger('resize');
});

You should add class="col-xs-12" to the chart or it's container.
You have not specified a HTML snippet, but it should be the element on which you cast the chart.

Related

How do I set a bar chart to default to a suggested maximum in chart.js v1.01?

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>

How to set width of bar dynamically in chart.js?

for one value the bar width is width of canvas so i want only to change the width of bar
how to fix the width of bar size ?
Check this out
barThickness
Manually set width of each bar in pixels. If not set, the base sample
widths are calculated automatically so that they take the full
available widths without overlap. Then, the bars are sized using
barPercentage and categoryPercentage.
Your code should be something like this:
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
xAxes: [{
barThickness: 10
}]
}
});
I made this example for you
Solution
You can set it on the Chart object
import {Chart} from "chart.js"
Chart.defaults.datasets.bar.barThickness = 73;
//also try barPercentage, maxBarThickness

Google chart is not taking full width while jquery show and hide

I am making a google chart whith show and hide functionality.Means chart will be hidden on the page load and when user clicks a button chart will be made visible.
My code
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var items = $(".label1").text();
var data = google.visualization.arrayToDataTable([
<%= chartItems %>
]);
var options = {
title: 'Poll Results'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="display:none; width:800px;height:500px;"></div>
My problem is that when user clicks on the button and chart is visible its not taking the full width and height(800x500).rather its taking an unknown dimension(400x200).
Note: when the chart is made visible in the page load itself, It works correctly.
Code is same change in HTML like this
<div id="chart_div" style=" width:800px;height:500px;"></div>
You can do as marios suggested and set dimensions inside that chart's options, but that won't fix all of the problems that come along with drawing a chart inside a hidden div. The Visualization APIs dimensional measurements don't work well inside hidden divs, so elements get positioned in the wrong place and have the wrong size in some browsers. You need to unhide the div immediately prior to drawing the chart, and you can hide it again when the chart is done drawing. Here's example code that does this:
var container = document.getElementById('chart_div');
container.style.display = 'block';
var chart = new google.visualization.PieChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
container.style.display = 'none';
});
chart.draw(data, options);
Use chartArea:{} to set width & height
function drawChart() {
var items = $(".label1").text();
var data = google.visualization.arrayToDataTable([
<%= chartItems %>
]);
var options = {
title: 'Poll Results',
chartArea: {
width: 800,
height: 500
}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I confirm that this is a bug. It work if the div is hidden "visibility:hidden;"
It does not work if the CSS shows "display:none"
There is an option to ask for specific width and height the google chart api https://developers.google.com/chart/interactive/docs/customizing_charts?hl=es.
Directly give width in chart option.
For eg:
options='{
"width": "800"
}'

How do you switch the cursor to a pointer cursor when hovering over the bars in a Kendo UI bar chart

I have a Kendo UI Datavis Bar Chart for which I wish to show the pointer (hand) cursor when hovering over the bars in the chart and labels for those bars. When moving off the bars in the chart the cursor should return to the standard arrow pointer.
I noticed that the cursor turned into the text cursor when hovering over the axis labels (left, right, and bottom) and on the legend. So in addition to the above I would like the cursor to remain the standard cursor (arrow) when hovering over the axis labels and legend (since you cannot edit these). I would also like the cursor to switch to the pointer cursor when hovering over the x-axis (bottom) labels.
I can easily show a pointer cursor for the entire chart when hovering anywhere over the chart but that is not desired.
I have tried various strategies using the seriesHover event but so far nothing has worked.
How do I achieve the above?
Thomas your answer almost has me there. However, I need one additional piece of information:
How would I use the technique you show in your answer below within a CSS file. I have several Kendo UI charts some for which I need this behavior and some for which I do not. I have both ids and classes associated with the divs that contain the kendo UI charts (one div per chart). The actual charts are created using JavaScript code at load time. I tried to add the following, to the CSS within the CSS file but this had no effect:
#barChart {
/*cursor: pointer;*/
(svg > path):last-child {cusror: pointer;}
}
where #barChart is the Id of the div containing the KendoUI chart within the HTML
<div id="barChart" class="bargraph"></div>
Is there a way to do what you have shown below for charts that are created at load time within predefined divs? Does this have to be done by hooking into the charts hover event?
Just tried styling the Kendo UI bar chart demo with CSS; both turning the cursor into a hand and leaving it the default cursor on text works quite well. I just had to add two lines of CSS (and change the script/CSS URLs):
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.3.1114/js/kendo.all.min.js"></script>
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.default.min.css" rel="stylesheet" />
<style type="text/css">
/* When hovering over a bar, Kendo dynamically adds
a bar as the last child of the SVG element that
works as an overlay. So, effectively, we're
hovering over the last (dynamically added) child */
svg > path:last-child {cursor:pointer;}
svg {cursor:default}
</style>
</head>
<body>
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart" style="background: center no-repeat url('../../content/shared/styles/world-map.png');"></div>
</div>
<script>
function createChart() {
$("#chart").kendoChart({
theme: $(document).data("kendoSkin") || "default",
title: {
text: "Internet Users"
},
legend: {
position: "bottom"
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "bar"
},
series: [{
name: "World",
data: [15.7, 16.7, 20, 23.5, 26.6]
}, {
name: "United States",
data: [67.96, 68.93, 75, 74, 78]
}],
valueAxis: {
labels: {
format: "{0}%"
}
},
categoryAxis: {
categories: [2005, 2006, 2007, 2008, 2009]
},
tooltip: {
visible: true,
format: "{0}%"
}
});
}
$(document).ready(function() {
setTimeout(function() {
// Initialize the chart with a delay to make sure
// the initial animation is visible
createChart();
$("#example").bind("kendo:skinChange", function(e) {
createChart();
});
}, 400);
});
</script>
</div>
<script type="text/javascript">
console.log("hi")
document.addEventListener("click",function(e){document.write(e.target)},false)
</script>
</body>
</html>​
If you have multiple charts and want this behavior only for some charts, I'd suggest using classes, like
<div id="barChart" class="bargraph cursorPointer"></div>
And change the CSS like
.cursorPointer svg > path:last-child {cursor:pointer;}
.cursorPointer svg {cursor:default}
(If you want the arrow cursor on text of all graphs, omit the .cursorPointer on the second line.)
If you want to change the cursor only in those labels where you have defined axisLabelClick event. You can do this:
var chart = $("#chart").data("kendoChart");
In my case, I just handle the first label, so I only want the pointer cursor in there:
var idLabel = chart._plotArea.axisY.children[0].options.id;
$('#' + idLabel).css('cursor', 'pointer');
Interestingly enough this worked for me perfectly (Only Bar Chart Kendo 2016):
svg > g g g g g g {cursor:pointer;}
svg {cursor:default}
Since this isn't a setting in Kendo yet, as #ThomasW, wrote you need to find a way to target the overlay path that gets shown when you hover over the graph elements.
In my case I noticed that all of those overlays have fill-opacity="0.2" and this did the trick:
.kendo-chart-wrapper [fill-opacity="0.2"] {
cursor: pointer;
}

Remove padding or margins from Google Charts

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
var myData = {
'Mushrooms': 3,
'Onions': 1,
'Olives': 1,
'Zucchini': 1,
'Pepperoni': 2
};
var rows = [];
for (element in myData) {
rows.push([element + " (" + myData[element] + ")", myData[element]])
}
data.addRows(rows);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':450,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Example fiddle
How do I remove padding or margins in this example?
By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:
// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
'width': 350,
'height': 400,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'}
};
If you want to tune it more, try changing these values or using other properties from the link above.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.
For anyone interested, here is the actual solution:
... //rest of options
width: '100%',
height: '350',
chartArea:{
left:5,
top: 20,
width: '100%',
height: '350',
}
... //rest of options
The key here has nothing to do with the "left" or "top" values. But rather that the:
Dimensions of both the chart and chart-area are SET and set to the SAME VALUE
As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.
It's missing in the docs (I'm using version 43), but you can actually use the right and bottom property of the chart area:
var options = {
chartArea:{
left:10,
right:10, // !!! works !!!
bottom:20, // !!! works !!!
top:20,
width:"100%",
height:"100%"
}
};
So it's possible to use full responsive width & height and prevent any axis labels or legends from being cropped.
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
There is this possibility like Aman Virk mentioned:
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
But keep in mind that the padding and margin aren't there to bother you.
If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.
If you take away that margin then you will end up showing only a part of the labels or no labels at all.
So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.

Categories

Resources