Apexcharts update series - apexcharts

I want to change my widget but I only want to change
series: [<?php echo $data['campaign']['0']->report_summary->open_rate * 100?>],
To the new data I am getting something like series: [100], But this is not working
$(document).ready(function () {
var element = document.getElementById("kt_mixed_widget_18_chart");
var height = parseInt(KTUtil.css(element, 'height'));
if (!element) {
return;
}
var options = {
series: [<?php echo $data['campaign']['0']->report_summary->open_rate * 100?>],
chart.updateOptions([{
series: [newData]
}]);

This worked!
ApexCharts.exec('chart_id', 'updateSeries', [5]);

Related

Can the colors of bars in a bar chart be varied based on their value?

Using chart.js 2, can the colors of the bars in a bar-cart be varied based on their value?
For example, if the scale is 0 - 100, columns with 50% and above could be green, while 0-49% could be red.
As far as I know there is no configuration or callback for each individual point being drawn. The best way I can think of to do this would be to create a function that would modify your chart config/data object. This isn't the most elegant way to deal with the problem, but it would work.
The Fix
Pass your chart config/data object to a function that will add the background color.
Main Point of the example is function AddBackgroundColors(chartConfig)
Example:
function AddBackgroundColors(chartConfig) {
var min = 1; // Min value
var max = 100; // Max value
var datasets;
var dataset;
var value;
var range = (max - min);
var percentage;
var backgroundColor;
// Make sure the data exists
if (chartConfig &&
chartConfig.data &&
chartConfig.data.datasets) {
// Loop through all the datasets
datasets = chartConfig.data.datasets;
for (var i = 0; i < datasets.length; i++) {
// Get the values percentage for the value range
dataset = datasets[i];
value = dataset.data[0];
percentage = value / range * 100;
// Change the background color for this dataset based on its percentage
if (percentage > 100) {
// > 100%
backgroundColor = '#0000ff';
} else if (percentage >= 50) {
// 50% - 100%
backgroundColor = '#00ff00';
} else {
// < 50%
backgroundColor = '#ff0000';
}
dataset.backgroundColor = backgroundColor;
}
}
// Return the chart config object with the new background colors
return chartConfig;
}
var chartConfig = {
type: 'bar',
data: {
labels: ["percentage"],
datasets: [{
label: '100%',
data: [100]
}, {
label: '50%',
data: [50]
}, {
label: '49%',
data: [49]
}, {
label: '5%',
data: [5]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
chartConfig = AddBackgroundColors(chartConfig);
var myChart = new Chart(ctx, chartConfig);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.bundle.min.js"></script>
<canvas id="canvas" width="400" height="200"></canvas>
In Chart.js 2 it is possible to set multiple colors with an array.
So you can define the backgroundColor as an array of color strings, matching the datasets data.
var myChart = new Chart(ctx, {
datasets: [{
label: 'Votes',
data: [1, 2, 3],
// Make the first bar red, the second one green and the last one blue
backgroundColor: ['#f00', '#0f0', '#00f']
}]
});
You can easily generate an array based on the values in data:
function getColorArray(data, threshold, colorLow, colorHigh) {
var colors = [];
for(var i = 0; i < data.length; i++) {
if(data[i] > threshold) {
colors.push(colorHigh);
} else {
colors.push(colorLow);
}
}
return colors;
}
See this fiddle for a working demo

Google Chart - Centering Annotations

I simply want to "center" the annotation in the bars in this chart. You can see how the data appear at the end of the bar. Can that percentage be centered in the bar?
Try as I might, I cannot figure it out. I found a block of code that was described as a hack, but it would have to be customized for each chart. I use this code to generates lots and lots of charts. Any help would be wildy appreciated!
function drawVisualizationstack(qid,cdata, w,h,l,cw,pos,stacked,questioncase) {
pos='top';
var data = new google.visualization.DataTable();
var e;
for (var k=0;k<cdata.length;k++) {
e=cdata[k];
if (e[0]=='column') {
if (e[2]=="tooltip") {
data.addColumn({type:'string',role:'tooltip','p':{'html':true}});
//data.addColumn({type: 'string', role: 'annotation','p':{'html':true}});
}
else if (e[2]=="annotation") {
data.addColumn({type: 'string', role: 'annotation', p: {html: true}});
}
else {
if (e[2]=="All") e['2']="All";
data.addColumn(e[1],e[2]);
}
}
else {
if (e==="" || e===undefined) {mclog('UNDEFINED DATA ROW FOR ' + qid);}
else {
data.addRow(e);
}
}
}
h=h*.75;
var chartHeight=h-65;
var options = {
width:500,
height:h,
isStacked:true,
chartArea:{height:chartHeight,left:l,width:cw},
backgroundColor:'transparent',
bar:{groupWidth:'80%'},
tooltip: {isHtml:true},
legend:{position:'none'},
hAxis: {title: 'Percentage',minValue:0,maxValue:100},
hAxis: {textPosition: 'none',ticks: [0]},
colors: ['#5d5d5d', '#002e32', '#0e1a40', '#364940', '#a9b861', '#404000', '#504000', '#604000', '#003070', '#687000'] //set default colors for charts
}}},
true,italic: true,color: '#871b47',auraColor: '#d799ae',opacity: 0.8}}
}
var chart = new google.visualization.BarChart(document.getElementById('questchart_'+qid));
jQuery("base").attr('href',document.location);
chart.draw(data,options);
}

Chart.js how to rewrite x for webAPP

I use chart.js for a webApp, but it is not I want.
How to rewrite this x axle or I should change other js to draw chart,demo:
You could extend the chart to remove the points that you don't need from the x-axis, like so (adapted from https://stackoverflow.com/a/31606933/360067)
Chart.types.Line.extend({
name: "LineAlt",
initialize: function (data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
if (this.options.every) {
var every = this.options.every;
var xLabels = this.scale.xLabels
xLabels.forEach(function (label, i) {
if (i % every !== 0)
xLabels[i] = '';
})
}
}
});
and you call it like so
var ctx = document.getElementById("chart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
every: 3
});
Adjust every to 2, 3,... to show one in every 2, every 3,... points.
Fiddle - http://jsfiddle.net/3p2ekjyn/

Google Chart: How to change option for dynamic length of series

There is data for google chart in JSON format from server and I instantiate Google Chart DataTable like this
var google_graph = new google.visualization.DataTable(json_data_from_server);
Then I set options for the chart, ComboChart(Bar + Line). I try to set the last series(number 11) to line chart but the number of series changes based on query.
var options = {
title: 'Combo Chart',
seriesType: "bars",
series: {
11: {
type: 'line',
}
}
};
Is there other way something like code below?
var options = {
title: 'Combo Chart',
seriesType: "bars",
series: {
getNumberOfColumns(): {
type: 'line',
}
}
};
Try doing:
var last = google_graph.getNumberOfColumns() -1; // if it doesn't work, change -1 to -2
var options = {
title: 'Combo Chart',
seriesType: "bars",
series: {
}
}
};
options.series[last]={type:''line'}

Google Charts - Hide line when clicking legend key

I'd like to be able to show/hide the lines on my line graph when clicking the relevant key in the legend, is this possible?
To hide show lines on your GWT Visualization LineChart, follow these steps:-
1.Create a DataView object based on an existing DataTable object:
DataTable dataTable = DataTable.create();
DataView dataView = DataView.create(dataTable);
2.Hide the column of the curve/line that you want to hide in the DataView:
dataView.hideColumns(new int[]{<id_of_the_column>});
3.Draw the entire chart again based on the DataView:
chart.draw(dataView, getOptions());
Please note that there is a caveat here, step 3 is a costly step, for us it is taking almost 20-30 sec. for the the new graph to be drawn. But if the data is not large it should be manageable in your context.
Note: You will have to make your own legend with a checkbox and do the above stuff when user checks/unchecks a checkbox.
If you don't need to include scaling and animation then one option is just hide data using lineWidth and areaOpacity values;
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script>
function updateTable() {
// quick data - cleaned up for this example real data sources
data = new Array();
data[0] = new Array();
data[0][0] = "Day";
data[0][1] = "Metric 1";
data[0][2] = "Metric 2";
data[0][3] = "Metric 3";
data[1] = new Array();
data[1][0] = 1;
data[1][1] = 200;
data[1][2] = 50;
data[1][3] = 400;
data[2] = new Array();
data[2][0] = 2;
data[2][1] = 440;
data[2][2] = 140;
data[2][3] = 40;
data[3] = new Array();
data[3][0] = 3;
data[3][1] = 300;
data[3][2] = 500;
data[3][3] = 600;
var gdata = google.visualization.arrayToDataTable(data);
var options = {
// title: 'kala',
hAxis: {title: 'Days', titleTextStyle: {color: '#333'}}
,vAxis: {minValue: 0}
,height: 300
,width: 600
,chartArea: {left: 60}
,lineWidth: 2
,series: {0:{color: 'black', areaOpacity: 0.3, lineWidth: 2}
,1:{color: 'red', areaOpacity: 0.3, lineWidth: 2}
,2:{color: 'purple', areaOpacity: 0.3, lineWidth: 2}}
};
var chart = new google.visualization.AreaChart(document.getElementById('my_chart'));
chart.draw(gdata, options);
google.visualization.events.addListener(chart,
'select',
(function (x) { return function () { AreaSelectHander(chart, gdata, options)}})(1));
}
function AreaSelectHander(chart, gdata, options) {
// when ever clicked we enter here
// more code needed to inspect what actually was clicked, now assuming people
// play nicely and click only lables...
var selection = chart.getSelection();
var view = new google.visualization.DataView(gdata);
console.log(options);
// click and data index are one off
i = selection[0].column - 1;
// just simple reverse
if (options.series[i].lineWidth == 0) {
options.series[i].lineWidth = 2;
options.series[i].areaOpacity = 0.3;
}
else {
options.series[i].lineWidth = 0;
options.series[i].areaOpacity = 0.0;
}
chart.draw(gdata, options);
}
</script>
<script type='text/javascript'>
google.load('visualization', '1', {packages:['table', 'corechart']});
google.setOnLoadCallback(updateTable);
</script>
</head>
<body>
<div id='my_chart'></div>
</body>
Following code display goggle line chart and have functionality to hide/show graph line by clicking on legend label. #graph_sales_data is id of div which display chart and sales_data_graph is variable containg record.
function drawChart() {
if (sales_data_graph.length > 1)
{
$('#graph_sales_data').show();
var data = new google.visualization.arrayToDataTable(sales_data_graph);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'graph_sales_data',
dataTable: data,
colors: ['#ea6f09', '#fb250d', '#0ac9c6', '#2680be', '#575bee', '#6bd962', '#ff0000', '#000000'],
options: {
width: 1200,
height: 500,
fontSize: 10,
pointSize: 10
}
});
// create columns array
var columns = [0];
/* the series map is an array of data series
* "column" is the index of the data column to use for the series
* "roleColumns" is an array of column indices corresponding to columns with roles that are associated with this data series
* "display" is a boolean, set to true to make the series visible on the initial draw
*/
var seriesMap = [{
column: 1,
roleColumns: [1],
display: true
}, {
column: 2,
roleColumns: [2],
display: true
}, {
column: 3,
roleColumns: [3],
display: true
}, {
column: 4,
roleColumns: [4],
display: true
}, {
column: 5,
roleColumns: [5],
display: true
}, {
column: 6,
roleColumns: [6],
display: true
}, {
column: 7,
roleColumns: [7],
display: true
}, {
column: 8,
roleColumns: [8],
display: true
}];
var columnsMap = {};
var series = [];
for (var i = 0; i < seriesMap.length; i++) {
var col = seriesMap[i].column;
columnsMap[col] = i;
// set the default series option
series[i] = {};
if (seriesMap[i].display) {
// if the column is the domain column or in the default list, display the series
columns.push(col);
}
else {
// otherwise, hide it
columns.push({
label: data.getColumnLabel(col),
type: data.getColumnType(col),
sourceColumn: col,
calc: function() {
return null;
}
});
// backup the default color (if set)
if (typeof(series[i].color) !== 'undefined') {
series[i].backupColor = series[i].color;
}
series[i].color = '#CCCCCC';
}
for (var j = 0; j < seriesMap[i].roleColumns.length; j++) {
//columns.push(seriesMap[i].roleColumns[j]);
}
}
chart.setOption('series', series);
function showHideSeries() {
var sel = chart.getChart().getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row == null) {
var col = sel[0].column;
if (typeof(columns[col]) == 'number') {
var src = columns[col];
// hide the data series
columns[col] = {
label: data.getColumnLabel(src),
type: data.getColumnType(src),
sourceColumn: src,
calc: function() {
return null;
}
};
// grey out the legend entry
series[columnsMap[src]].color = '#CCCCCC';
}
else {
var src = columns[col].sourceColumn;
// show the data series
columns[col] = src;
series[columnsMap[src]].color = null;
}
var view = chart.getView() || {};
view.columns = columns;
chart.setView(view);
chart.draw();
}
}
}
google.visualization.events.addListener(chart, 'select', showHideSeries);
// create a view with the default columns
var view = {
columns: columns
};
chart.draw();
}
else
{
$('#graph_sales_data').hide();
}
}