morris.js line update ymin - javascript

Is there any way to update the ymin of a morris.js line/area?
I've tried it with:
chart.ymin = 10
but the ymin is still 0.
When it`s not possible in morris.js, are there any other chart libarys that include such a feature?

Solution 1
Make sure you set the Morris parameter resize to true.
Then, on your action, you can set the ymin, redraw the chart and make sure the chart is well positioned (trigger a window resize):
chart.ymin = 10;
chart.redraw();
$(window).trigger("resize");
Please try the following snippet:
var data = [
{ Date: '2016-01-01', Sales: 10 },
{ Date: '2016-01-02', Sales: 20 },
{ Date: '2016-01-03', Sales: 40 },
{ Date: '2016-01-04', Sales: 5 },
{ Date: '2016-01-05', Sales: 50 }
];
var chart = new Morris.Line({
element: 'chartLine',
data: data,
xkey: 'Date',
ykeys: ['Sales'],
labels: ['Sales'],
resize: true,
xLabels: 'day',
parseTime: false
});
$(".ymin").on("click", function() {
chart.ymin = 10;
chart.redraw();
$(window).trigger("resize");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" rel="stylesheet" />
<div id="chartLine"></div>
<div class="ymin">Set ymin</div>
Solution 2
Set the Morris parameter resize to false for your temperature chart.
Make sure you include the Morris CSS available on the Morris GitHub. Without this CSS, hovering the chart will display the data at the bottom of the chart and will hide the x axis on the next data update from the setInterval.
Remove the code trying to get/set the chart height, triggering a window resize and calling the temperature chart redraw.
Finally add the following code in your $(document).ready function:
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function () {
delay(function () {
TemperatureChart.redraw();
}, 300);
}).trigger('resize');
Please try the following fork of your CodePen: codepen.io/krlzlx/pen/prwMLr

Related

Make events run multiple times, Highcharts

I have a Highchart in which under the options object I have events object as ashown below.
var options = {
chart: {
renderTo: 'container',
type: 'line',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
var series = this.series[0],
chart = this;
...// Some Code
}
}
So what I want is that I need events data to update dynamically and load the Highcharts only once.
How can I make the Following section dynamic so that the values in it change dynamically. Keeping in mind that Highcharts container have to be defined and load only once.
events: {
load: function() {
var series = this.series[0],
chart = this;
...// Some Code
}
}
One of the official Highcharts demos shows how to achieve it. Take a look at it:
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/dynamic-update/
Highcharts also offers other options to update the chart with new data, API:
https://api.highcharts.com/class-reference/Highcharts.Chart#addSeries
https://api.highcharts.com/class-reference/Highcharts.Series#update
https://api.highcharts.com/class-reference/Highcharts.Series#setData

Amcharts add value to dataset from external source (temperatue)

I have a temperature sensor connected over http and I would like to add temperature to the Amcharts every 5 seconds. Have someone some example how to add new value to the current dataset? I will use line chart to represent temperature on y axis and datetime on x
thank you
The general idea behind dynamically updating a chart is to add a new element to your chart's dataProvider then call its validateData method. While it doesn't use AJAX, this demo basically has the framework laid out for you in the function that is called in the setInterval call:
setInterval( function() {
// make your ajax call here, then on a successful callback:
// add data item to the array
chart.dataProvider.push( {
/* new data */
} );
chart.validateData();
}, 5000 );
It also shifts the old data off the chart, which you may want to consider if you have a lot of data points added to the chart. A regular serial chart's performance will degrade after several hundred to a thousand points or so.
Ok.. I have done this example but it only shows me one value. Is this because the charData[] (array) contains only one value? (in the generateChartData function)
What I want is to draw a random value each second and push each time the graph to the left side..
here is example (copy/paste)
<!DOCTYPE html>
<html>
<head>
<title>chart created with amCharts | amCharts</title>
<meta name="description" content="chart created using amCharts live editor" />
<!-- amCharts javascript sources -->
<script type="text/javascript" src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="https://www.amcharts.com/lib/3/serial.js"></script>
<!-- amCharts javascript code -->
<script type="text/javascript">
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var chartData = generateChartData();
function generateChartData() {
var chartData = [];
var firstDate = new Date();
firstDate.setSeconds( firstDate.getDate());
chartData.push( {
date: firstDate,
temp: 0
} );
return chartData;
}
var timeout;
setInterval( function() {
chart.dataProvider.shift();
var newDate = new Date();
var temp = Math.round( Math.random() * 40 + 100 );
// dodamo podatek v graf
chart.dataProvider.push( {
date: newDate,
temp: temp
} );
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(function () {
chart.validateData();
});
}, 1000 );
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": chartData,
"valueAxes": [ {
"position": "left",
"title": "Temperatura v °C"
} ],
"graphs": [ {
"valueField": "temp"
} ],
"categoryField": "date",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
}
} );
</script>
</head>
<body>
<div id="chartdiv" style="width: 100%; height: 400px; background-color: #FFFFFF;" ></div>
</body>
</html>

c3.js tooltip - make static and style

I have a c3.js stacked barchart that updates when you hover over a Leaflet map, and I need the tooltip to be static as otherwise the user will hover over other areas of the map and change the data in the barchart, before actually reaching it. However, I'm new to coding and especially new to C3 and I can't get around how to make the tooltip static. Also, does anyone know how to style the tooltip later? I have only found very complex examples online, but it feels like I should be able to do it somewhere after I generate the chart.
Any help would be much appreciated!
Here is my code:
function getMiniChartData(properties) {
var values = [
['rape', rape[properties['gss_code']]],
['other sexual', other_sexual[properties['gss_code']]]];
console.log(values);
return values;
}
var chart;
function drawMiniChart(properties) {
console.log('drawing mini chart');
var data = getMiniChartData(properties);
chart = c3.generate({
bindto: '#minichart',
color: {
pattern: ['#E31A1C', '#BD0026']
},
point: {
show: false
},
tooltip: {
show: true
},
data: {
columns: data,
type: 'bar',
groups: [
['rape', 'other sexual']
]
},
axis: {
y: {
max:60,
min:0
}
},
grid: {
y: {
lines: [{
value: 0
}]
}
}
});
}
function updateMiniChartData(properties) {
console.log('updating mini chart');
var data = getMiniChartData(properties);
chart.load({
columns: data
});
}
Just edit the position in the tooltip :
position: function () {
var position = c3.chart.internal.fn.tooltipPosition.apply(this, arguments);
position.top = 0;
return position;
}
This will set the tooltip to always be at the top of the point. So it stays at the same y coordinate (top:0) but follows the points x value. You could go further and set it to stay at one position on the page.
Check this fiddle I have put together : http://jsfiddle.net/thatOneGuy/owhxgaqm/185/
This question will help you out : C3 charts - contents of tooltip clickable
If you want it visible all the time just add this code :
var originalHideTooltip = chart.internal.hideTooltip
chart.internal.hideTooltip = function () {
setTimeout(originalHideTooltip, 100)
};

how to focus the clicked bar in C3.js bar graph?

I have this code which makes a graph using c3.js : https://jsfiddle.net/1bxe2scd/
<!DOCTYPE html>
<html>
<head>
<title>Dsnap - Charts</title>
<!-- Load c3.css -->
<link href="c3/c3.css" rel="stylesheet" type="text/css">
<!-- Load d3.js and c3.js -->
<script src="d3/d3.min.js" charset="utf-8"></script>
<script src="c3/c3.min.js"></script>
</head>
<body>
<div id="chart" style="width:480px;height:400px"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var chart = c3.generate({
bar: {
width: 15
},
padding: {
left: 60
},
data: {
x: 'Date',
columns:
[
['Date', '2011-02','2013-01','2013-02','2013-03','2013-04','2013-05','2013-06','2013-07','2013-08','2013-09','2013-10','2013-11','2013-12','2014-01','2014-02'],
['value', 777,53,165,269,344,376,410,421,405,376,359,392,433,455,978]
],
type: 'bar',
onclick: function(e) { console.log(e.x);}
},
axis: {
rotated: true,
x: {
type: 'category'
}
},
tooltip: {
grouped: false
},
legend: {
show: false
}
});
</script>
</body>
</html>
I want the bar on which the user clicks to be focused and the rest of the bar should become faded, how can I achieve that?
How can I get the Y value of the clicked bar(eg: 2011-02 etc)?
You can do this for highlighting the bar:
onclick: function(e) {
//make all the bar opacity 0.1
d3.selectAll(".c3-shape").style("opacity",0.1);
var k = ".c3-shape-"+ e.index;
//make the clicked bar opacity 1
d3.selectAll(k).style("opacity",1)
}
Working code here
On clicking out side in the chart if you wish to bring back all the bars attach the click listener to the chart and on click make all bar's opacity 1:
d3.selectAll("#chart").on("click", function(d) {
//reset all the bars
d3.selectAll(".c3-shape").style("opacity", 1);
})
Working code here
EDIT
So now since you have two charts specify the id also to make it specific to the chart note the id in the selector: (#chart/#chart1):
d3.selectAll("#chart1").on("click", function(d) {
//reset all the bars for chart1
d3.selectAll("#chart1 .c3-shape").style("opacity", 1);
})
d3.selectAll("#chart").on("click", function(d) {
//reset all the bars for chart
d3.selectAll("#chart .c3-shape").style("opacity", 1);
})
On click for chart1 bar will look like this:
onclick: function(e) {
//make all the bar opacity 0.1 for chart1
d3.selectAll("#chart1 .c3-shape").style("opacity", 0.1);
var k = "#chart1 .c3-shape-" + e.index;
//make the clicked bar opacity 1
d3.selectAll(k).style("opacity", 1)
event.stopPropagation()
}
Working code here
Hope this helps!
C3 has callbacks, for specifying what should happen when a click (or mouseover/mouseout) event occurs:
http://c3js.org/reference.html#data-onclick
It also has "APIs": functions you can call to basically act like the user made a selection or focused:
http://c3js.org/reference.html#api-focus
You could hook one of these up to trigger the other, like have the onclick() function call focus().
But given what you're precisely looking for, the impediment would be that the focus() function doesn't accept the indices of individual bars on the graph. So it can only highlight an entire column/series of data at once, not individual bars. Here's the GitHub issue:
https://github.com/c3js/c3/issues/1389

Pie chart using flot

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.

Categories

Resources