C3 bar chart with 3 variables - angularjs

I'm trying to display chart like this one, with following data:
[{"name":"doctor","monetary":"on","number":57},{"name":"programmer","monetary":"non-monetary","number":15}]
but I can't group monetary on or of value with the rest of the data.
Is there some other way to display chart with these data?
Here is the definition in controller:
$scope.chart = c3.generate({
bindto: d3.select('#chart'),
data: {
json: $scope.data,
columns: [
['monetary'],
['number']
],
keys: {
value: ['doctor', 'programmer']
},
groups: [
['number'],['monetary']
],
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
},
});
},
function formatData ( json ) {
var formattedData = [],
object = {};
// fill object with data
angular.forEach(json, function(row) {
if (row.hasOwnProperty('name') && row.hasOwnProperty('number')) {
this[row.name] = row.number;
}
},object);
formattedData.push(object); // push c3 object in the array
return formattedData;
}
}]);

Remove this part of code if I am not wrong then it will display separately
groups:
[ ['number'],['monetary']],
After modification the code is as below and also a fiddle link has been given.
var chart = c3.generate({
data: {
columns: [
['MONETARY', 0, 3259, 10415, 14660, 2950, 16705, 22255, 4000],
['NON-MONETARY', 12335, 18041, 35900, 21985, 15110, 370, 13055, 20740]
],
type: 'bar',
},
axis: {
x: {
type: 'category',
categories: ['DENTIST', 'PROGRAMMER/ANALYST', 'CORPORATE SECRETARY', 'PHYSICIAN', 'PROFESSOR', 'PRESIDENT', 'MANAGER', 'CO-OWNER']
}
}
});
See the modified fiddle:
http://jsfiddle.net/63cp42Lv/4/

Related

How to use convert date in billboardJS

it's the first time i am using billboard.js so i'm having difficulties working with timeseries data, here's my try:
exemple of the data:
{
"values":{
[5,8],[2020-02-07T07:06:01.591Z,2020-02-07T07:06:03.812Z]
}
}
how i'm trying to display it (not sure if MS exists):
chart = bb.generate({
bindto: "#chart",
data: {
x: "x",
xFormat: "%Y-%m-%dT%H:%M:%S.%MSZ",
type: "line",
columns: [
["x",data.values[1]],
["nbr evenements",data.values[0]]
]
},
axis:{
x:{
type:"timeseries",
localtime:false,
tick: {
format: "%Y-%m-%d %H:%M:%S.%MS"
}
}
}
});
i tried this instead, it worked fine:
chart = bb.generate({
bindto: "#chart",
data: {
x: "x",
xFormat: "%Y-%m-%dT%H:%M:%S.%LZ",
type: "line",
columns: [
["x"].concat(data.values[1]),
["nbr evenements"].concat(data.values[0])
]
},
axis:{
x:{
type:"timeseries",
localtime:false,
tick: {
format: "%Y-%m-%dT%H:%M:%S"
}
}
}
});

How can I display the current value from a chart?

I am new to React and I work on a small project basically, I have a chart and I just want to display the current value from the chart.
For example, I have a chart with 4 random values:[5,2,5,1], so I want to have displayed the current value below the chart like first is 5, second is 2 and so on.
Here is my part of code:
class App extends React.Component {
addPoint = (point) => {
currentData = this.state.options.series[0].data
this.setState({
options: {
series: [
{ data: [...currentData, point]}
]
}
});
}
constructor(props) {
super(props);
this.internalChart = undefined;
this.dataStream = new DataStream();
this.dataStream.setUpdateCallback(this.addPoint);
this.state = {
options: {
chart: {
events: {
load: function () {
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 2
},
title: {
text: 'Live random data'
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: [[(new Date()).getTime(), 0]]
}]
}
};
}
render() {
return (
<HighchartsReact
constructorType={"stockChart"}
highcharts={Highcharts}
options={this.state.options}
/>
);
}}
Based on your snippet code, try to make random method by using function
Math.floor(Math.random() * Math.floor(max))
And then assign the options to HighchartsReact,
Full code on sandbox: https://codesandbox.io/s/headless-dream-0lzj1

Display highcharts graph with a lot of data in angularjs

I have an angularjs application and I use highcharts-ng to display some graphs. I got the data from an http request and I modify the data to display them in the graph.
If I receive just a just some data, it's ok, it works but when I receive a lot of data, the highcharts component take a long time to display the data. And in this time the browser in freezed.
In my controller, I have:
widgetCtrl.chartDataLine = {
chart: {
type: 'spline',
zoomType: 'xy'
},
title: {
text: 'Power Consumption'
},
xAxis: {
type: 'datetime',
title: {
text: 'Date time'
}
},
yAxis: {
title: {
text: 'Power (W)'
},
min: 0
},
options: {
exporting: {
enabled: true,
allowHTML: true,
buttons: {
contextButton: {
menuItems: null,
onclick: function () {
this.exportChart();
}
}
}
}
},
plotOptions:{
series:{
turboThreshold:60000 // larger threshold or set to 0 to disable
}
},
series: []
};
I call the data like that:
var getMetrics = function (searchText) {
var param = {
target: searchText
};
xcsDatasource.get('beo').callAction('getPowerMetrics', param.target, widgetCtrl.pickerFrom.date, widgetCtrl.pickerTo.date).then(
function (result) {
widgetCtrl.metrics = result;
widgetCtrl.metricsAsString = JSON.stringify(result);
var t = getChartData(result);
widgetCtrl.chartDataLine.series = angular.copy(t);
console.log(widgetCtrl.chartDataLine);
//widgetCtrl.chartDataArea.series = getChartData(result);
},
function () {
widgetCtrl.metrics = {};
widgetCtrl.metricsAsString = '';
}
);
};
And this is my html:
<div ng-if="config.linechart" class="graph-container col-sm-12">
<highchart id="chart1" config="pwrDashboardViewCtrl.chartDataLine"></highchart>
</div>
Do you have an idea how I can do to continue to load the grapph without freezing the browser ?

Export Google Chart to Excel Sheet in Angular

Im using ng-google-chart to create charts from data I receive from a database. I store the data in a table. I need to export both the table and the chart.
I'm using the following technique to export tables (where "exportable" is the div the contains the table):
$scope.export = function ()
{
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Record.xls");
alert("export done");
};
I cannot find any way to add the chart to this file.
This is the code to generate a chart
var chart1 = {};
chart1.type = "ColumnChart";
chart1.cssStyle = "height:400px; width:500px;";
chart1.data = {
"cols": [
{ id: "gender", label: "Gender", type: "string" },
{ id: "number", label: "number", type: "number" }
], "rows": [
{
c: [
{ v: "male" },
{ v: $scope.male, f: $scope.male }
]
},
{
c: [
{ v: "female" },
{ v: $scope.female }
]
}
]
};
chart1.options = {
"title": "",
"isStacked": "true",
"fill": 20,
"displayExactValues": true,
"vAxis": {
"title": "Number", "gridlines": { "count": 6 }
},
"hAxis": {
"title": "gender"
}
};
chart1.formatters = {};
$scope.chart = chart1;
}
To getImageURI of the chart, wait for the ready event and call the function.
Then you can add the image somewhere on the page.
You can even hide the original chart if needed...
Following is an example of loading the image URI into another element.
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
google.visualization.events.addListener(chart, 'ready', function () {
document.getElementById("chart_image").insertAdjacentHTML('beforeEnd', '<img alt="Chart Image" src="' + chart.getImageURI() + '">');
});
chart.draw(view, options);
}
<script src="https://www.google.com/jsapi"></script>
<span>CHART</span>
<div id="chart_div"></div>
<br/>
<span>IMAGE</span>
<div id="chart_image"></div>

Want to call a function when chart is loaded rally

Want to call a function when chart is loaded, written that function in listeners, but its getting called before the chart is displayed, any idea which event should I listen to chartRendered or any other
getChartConfig: function(project_oid) {
that = this;
var chart = Ext.getCmp('mychart');
if (chart) {
chart.destroy();
}
return {
xtype:'rallychart',
id: 'mychart',
storeConfig: {
find: {
'_ProjectHierarchy': project_oid,
"$or": [
{"_TypeHierarchy": "HierarchicalRequirement"},
{"_TypeHierarchy": "Defect"}
],
'Children': null
},
fetch: ['PlanEstimate','_TypeHierarchy','ObjectID', 'ScheduleState', '_ValidFrom', '_ValidTo', '_PreviousValues'],
hydrate: ['ScheduleState', '_TypeHierarchy'],
sort: { '_ValidFrom': 1 }
,
/*find: {
'_ProjectHierarchy': project_oid,
"_TypeHierarchy": {
"$in": ['HierarchicalRequirement', 'Defect']
},
'Children': null
},
fetch: ['PlanEstimate','_TypeHierarchy','ObjectID', 'ScheduleState', '_ValidFrom', '_ValidTo', '_PreviousValues'],
hydrate: ['ScheduleState', '_TypeHierarchy'],
sort: { '_ValidFrom': 1 }*/
},
calculatorType: 'CycleCalculator',
chartColors: [ "#6AB17D", "#F47168", "#000000"],
calculatorConfig: {
startDate: Rally.util.DateTime.format(new Date(this._startDate), 'Y-m-d'),
endDate: Rally.util.DateTime.format(new Date(this._endDate), 'Y-m-d'),
startState: this._startState,
endState: this._endState
//granularity: 'week'
},
chartConfig: {
chart: {
type: 'line',
},
title: { text: 'Cycle/Lead Time' },
border: 1,
plotOptions: {
series: {
connectNulls: true,
marker: {
enabled:false
}
}
},
xAxis: {
//tickmarkPlacement: 'on',
tickInterval: 10,
title: {
text: 'Months'
}
},
yAxis: [
{
title: {
text: 'Average Days'
}
}
]
},
listeners: {
snapshotsAggregated: this.showStats,
scope: this
}
}
},
below the is function I want to call
And in showStats() function I want use chart object,,,,please help..thanks in advance
showStats: function(chart) {
console.log("chart values", chart);
var average = Ext.Array.mean(chart.calculator.globalVar);
var average = Ext.Number.toFixed(average, 2);
var min = Ext.Array.min(chart.calculator.globalVar);
var max = Ext.Array.max(chart.calculator.globalVar);
var count = Ext.Array.sum(chart.calculator.globalVar);
console.log("field value", average, min, max, count);
//field.fieldLabel = average;
var stdDev = this.standardDeviation(average, chart.calculator.globalVar);
var stdDev = Ext.Number.toFixed(stdDev, 2);
this.down('#averageId').setText("Average " + average);
this.down('#countId').setText("Count " + count);
this.down('#minId').setText("Minimum " + min);
this.down('#maxId').setText("Maximum " + max);
this.down('#stdDevId').setText("Std Deviation " + stdDev);
},
Your choice of chartRendered is correct- that is the last one to fire.
If it is fires before the chart is fully rendered, it is a bug, but from my tests it looks like it fires at the right time. I do not know what data is stored in your globalVar and how you arrive at it. Perhaps the problem is somewhere else other then the timing of the chartRendered event.
When I modify this example by adding chartRendered event listener, visually the console.log may log a little faster than the chart animation entirely completes, but the chart data is already fully loaded by then, and all the data is complete. I verified that by building a table with a few stats that you use. Here is the full code:
Ext.define('Rally.example.BurnCalculator', {
extend: 'Rally.data.lookback.calculator.TimeSeriesCalculator',
config: {
completedScheduleStateNames: ['Accepted']
},
constructor: function(config) {
this.initConfig(config);
this.callParent(arguments);
},
getDerivedFieldsOnInput: function() {
var completedScheduleStateNames = this.getCompletedScheduleStateNames();
return [
{
"as": "Planned",
"f": function(snapshot) {
if (snapshot.PlanEstimate) {
return snapshot.PlanEstimate;
}
return 0;
}
},
{
"as": "PlannedCompleted",
"f": function(snapshot) {
if (_.contains(completedScheduleStateNames, snapshot.ScheduleState) && snapshot.PlanEstimate) {
return snapshot.PlanEstimate;
}
return 0;
}
}
];
},
getMetrics: function() {
return [
{
"field": "Planned",
"as": "Planned",
"display": "line",
"f": "sum"
},
{
"field": "PlannedCompleted",
"as": "Completed",
"f": "sum",
"display": "column"
}
];
}
});
var PI_OID = 12483739639; //The ObjectID of the PI on which to burn
Ext.define('Rally.example.BurnChart', {
extend: 'Rally.app.App',
requires: [
'Rally.example.BurnCalculator'
],
launch: function() {
this.add({
xtype: 'rallychart',
storeType: 'Rally.data.lookback.SnapshotStore',
storeConfig: this._getStoreConfig(),
calculatorType: 'Rally.example.BurnCalculator',
calculatorConfig: {
completedScheduleStateNames: ['Accepted', 'Released']
},
chartConfig: this._getChartConfig(),
listeners:{
chartRendered: this._getStats,
scope: this
}
});
},
/**
* Generate the store config to retrieve all snapshots for all leaf child stories of the specified PI
*/
_getStoreConfig: function() {
return {
find: {
_ItemHierarchy: PI_OID,
_TypeHierarchy: 'HierarchicalRequirement',
Children: null
},
fetch: ['ScheduleState', 'PlanEstimate'],
hydrate: ['ScheduleState'],
sort: {
_ValidFrom: 1
},
context: this.getContext().getDataContext(),
limit: Infinity
};
},
/**
* Generate a valid Highcharts configuration object to specify the chart
*/
_getChartConfig: function() {
return {
chart: {
defaultSeriesType: 'area',
zoomType: 'xy'
},
title: {
text: 'PI Burnup'
},
xAxis: {
categories: [],
tickmarkPlacement: 'on',
tickInterval: 5,
title: {
text: 'Date',
margin: 10
}
},
yAxis: [
{
title: {
text: 'Points'
}
}
],
tooltip: {
formatter: function() {
return '' + this.x + '<br />' + this.series.name + ': ' + this.y;
}
},
plotOptions: {
series: {
marker: {
enabled: false,
states: {
hover: {
enabled: true
}
}
},
groupPadding: 0.01
},
column: {
stacking: null,
shadow: false
}
}
};
},
_getStats:function(chart){
var stats = [];
console.log(chart);
var series = chart.chartData.series;
_.each(series, function(s){
stats.push({
name : s.name,
average : Ext.Number.toFixed(Ext.Array.mean(s.data), 2),
min : Ext.Array.min(s.data),
max : Ext.Array.max(s.data),
count : Ext.Array.sum(s.data)
});
});
this._showStats(stats);
},
_showStats: function(stats) {
console.log(stats);
this.add({
xtype: 'rallygrid',
store: Ext.create('Rally.data.custom.Store', {
data: stats
}),
columnCfgs: [
{
text: 'Name',
dataIndex: 'name'
},
{
text: 'Average',
dataIndex: 'average'
},
{
text: 'Min',
dataIndex: 'min'
},
{
text: 'Max',
dataIndex: 'max'
},
{
text: 'Count',
dataIndex: 'count'
}
]
});
}
});

Resources