I need to display every month User Revenue details in chart. Here I'm using PHP CodeIgniter frame work. In below I have mentioned my user controller:
public function Revenue_byuser() {
$rev_data = [];
$rev_array = [];
$getuser_info = $this->User_Model->getuser_alldetail();
for($i=0;$i<=count($getuser_info);$i++) {
$get_rev = $this->User_Model->getrev_byuserid($getuser_info[$i]->id);
foreach($get_rev as $key => $val) {
$rev_data[] = $val['total_revenue']??'0';
}
$rev_array[] = array('name' => $getuser_info[$i]->id, 'data' => $rev_data);
}
$Return['revenue_data'] = $rev_array;
$this->resp_output($Return);
exit;
}
My User Model:
public function getuser_alldetail() {
return $this->db->get_where('login', ['dept' => 1, 'status' => 1])->result() ;
}
public function getrev_byuserid($userid) {
$query = "select sum(revenue) as total_revenue,DATE_FORMAT(upd_date,'%Y-%m') AS revmonth from revenue_details WHERE added_by = ? AND DATE_FORMAT(upd_date, '%y') = DATE_FORMAT(CURRENT_DATE, '%y') GROUP BY revmonth ORDER BY revmonth ASC";
return $this->db->query($query,[$bdid])->result_array();
}
And This chart.js file:
$(window).on("load", function(){
var siteurl = window.location.origin;
$.ajax({
url: siteurl+'/User/Revenue_byuser',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resp) {
var revuser_option = {
chart: {
height: 250,
type: 'line',
toolbar:{
show: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
series: resp.revenue_data,
xaxis: {
type: 'date',
categories: ["Jan", "Feb", "Mar", "April", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
},
tooltip: {
x: {
format: 'dd/MM/yy'
},
},
colors: ['#111211','#15ad15','#0cebdc','#f21335','#f2b313','#131ff2','#cd13f2','#111411','#16ad15','#2cebdc','#f28335','#f9b313']
};
var user_revenue = new ApexCharts(document.querySelector("#rev_byuser"),revuser_option);
user_revenue.render();
}
});
});
Then when print my response I'm getting same revenue details for all users.
But I want to print like this:
series: [{
name: 'Username-1',
data: [31, 40, 28, 51, 42, 109, 100, 17, 87, 12, 7, 89]
}, {
name: 'Username-2',
data: [33, 32, 76, 12, 44, 62, 31, 54,96,8,5,54]
},
{
name: 'Username-3',
data: [21, 50, 38, 41, 52, 10, 20]
}, {
name: 'Username-4',
data: [11, 32, 45, 32, 34, 52, 41]
}],
Where I made mistake here please help me out.
If I understand you correctly, you are experiencing an ever increasing array for rev_data. On the second line of the public function Revenue_byuser(), you specify $rev_data as such:
$rev_data = [];
A bit further on you fill that array with a new index:
foreach($get_rev as $key => $val) {
$rev_data[] = $val['total_revenue']??'0';
}
Problem is, you don't empty the array after you've add the data for that specific user. As such, you keep pushing data into an array which you re-use for each user.
To solve this, empty the array after you've added the data for a user:
$rev_array[] = array('name' => $getuser_info[$i]->id, 'data' => $rev_data);
$rev_data = [];
Related
I have difficulty in changing the color of the bars in the bar chart to suit the theme of my website. I have gone to youtube and watched the following video https://www.youtube.com/watch?v=Cw87VN7K1Ek
and tried their solution to change color but was not successful. I would like to seek your help to know where I may have gone wrong or changes that have to be made to my code to successfully display the new color.
The following is the code snippet to configure the bar chart:
constructor() {
this.chartOptions = {
series: [
{
name: "My-series",
data: [10, 41, 35, 51, 49, 62, 69, 91, 148]
}
],
chart: {
height: 350,
type: "bar"
},
title: {
text: "My First Angular Chart"
},
xaxis: {
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"]
},
fill: {
colors: ['#f00']
}
};
}
The following is the result, the colors of the chart is still the default color from ApexCharts
I also would like to change the color of a specific bar (data point) within the bar chart when selected. I have looked through the following link: https://apexcharts.com/docs/options/states/, but this only changes the shade but I like to change the color but have not seem to find any resource to go about do it. I would sincerely appreciate if you have experienced the following before and has managed to change it successfully.
You can try this configuration:
var options = {
chart: {
type: 'bar',
height: 'auto'
},
series: [{
name: "My-series",
data: [10, 41, 35, 51, 49, 62, 69, 91, 148]
}],
dataLabels: {
enabled: false
},
xaxis: {
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"]
},
colors: [
function ({ value, seriesIndex, dataPointIndex, w }) {
if (dataPointIndex == 8) {
return "#7E36AF";
} else {
return "#D9534F";
}
}
]
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
I hope it was helpful!
Below is the pen for different color options. It shows single color and changes to multi color after a delay just to showcase available options. Pick the one you like.
https://codepen.io/raevilman/full/dyXNgNo
Chart options used in above link.
var options = {
chart: {
type: "bar"
},
series: [
{
data: [10, 40, 20, 44, 22, 12]
}
],
xaxis: {
categories: [1, 2, 3, 4, 5, 6]
},
colors: ["#00FF00"]
};
PS: I couldn't get the way to change selection color for bar chart.
I am using highcharts and want to bind dynamic json data to pie chart.Here is my dynamic string
for(i = 0; i < month.length; i++){
pi_data+='{name:"'+month[i]+'",y: '+ percent[i] +',color: Highcharts.getOptions().colors['+ i
+']},';
}
Here i am generate json string and bind in pie chart data option below
{
type: 'pie',
name: 'Total Percentage',
data: [pi_data],
center: [100, 50],
size: 100,
showInLegend: false,
}
My return string is
{name:"January",y: 24.78,color: Highcharts.getOptions().colors[0]},{name:"February",y: 14.69,color: Highcharts.getOptions().colors[1]},{name:"March",y: 26.51,color: Highcharts.getOptions().colors[2]},{name:"April",y: 34.01,color: Highcharts.getOptions().colors[3]}
If i put directly in data option it working but if i put variable in data option(inside [ ] in data:) it wont work.
I guess you want data to be an array, not a string of JS code (what you get from the loop; it's also malformed), so you need to compose pi_data properly. Try this:
// From the loop I assumed pi_data should be an array.
let pi_data = []
for(i = 0; i < month.length; i++){
pi_data.push({
name: month[i],
y: percent[i],
color: Highcharts.getOptions().colors[i],
});
}
{
type: 'pie',
name: 'Total Percentage',
data: pi_data, // No []!
center: [100, 50],
size: 100,
showInLegend: false,
}
The way you are formatting the data is incorrect. data parameter takes an array of items, where as here your passing is an object.
Try converting it to the following format:
let pi_data = month.map((item,index) => ({
name: item.month,
y: item.percent,
color: Highcharts.getOptions().colors[index]
}));
//Result
[
{ name: "January", y: 24.78, color: Highcharts.getOptions().colors[0] },
{ name: "February", y: 14.69 , color: Highcharts.getOptions().colors[1]},
{ name: "March", y: 26.51,color: Highcharts.getOptions().colors[2] },
{ name: "April", y: 34.01,color: Highcharts.getOptions().colors[3] }
]
And in the options just have this array placed
{
type: 'pie',
name: 'Total Percentage',
data: pi_data,
center: [100, 50],
size: 100,
showInLegend: false,
}
Fiddle for your reference: https://jsfiddle.net/vo3ch9L1/
All,
I'm trying to change a Javascript var which I use to populate data on chart based on clicking an element, can't seem to get it to work. Can anyone help?
I have the variable below, I want to use the array below on my chart whenever I click an html element.
var monthActualLWDC = [12,54,65,74,23,47,75,23,57,65,45,33]
Element,
<a id="btn2" onclick="changeTheVariable()" value="monthActualLWDC" class="ui labeled button"></a>
Function,
function changeTheVariable() {
var chartdata = document.getElementById("btn2").value;
}
So when plug "chartdata" into the chart, it should display the "monthActualLWDC"
new Chart(document.getElementById("mixed-chart"), {
type: 'bar',
data: {
labels: ["Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "YTD", "P.FY"],
datasets: [{
label: "Month Actual",
type: "line",
borderColor: "#002db3",
data: chartdata,
fill: false
}, {
label: "Prev. Y. Month Actual",
type: "line",
borderColor: "#000d33",
data: monthActualPYLWD,
fill: false
}, {
label: "Goal",
type: "line",
borderColor: "#e60000",
data: goalLWD,
fill: false
}, {
label: "YTD & P.Fiscal Year",
type: "bar",
backgroundColor: "rgba(0,0,0,0.5)",
data: ytdpfyLWD,
},
]
},
options: {
title: {
display: true,
text: 'CDC - Champaign Distribution Center - KPI'
},
legend: { display: true }
}
});
I don't know what I'm doing wrong...need help.
The value of the input is just a string, it doesn't automatically get evaluated as the variable. If you want to access data using a string name, you should put it in an object whose property names are the strings.
var myData = {
monthActualLWDC = [12,54,65,74,23,47,75,23,57,65,45,33]
}
Then you can use the value as an index into the object:
function changeTheVariable() {
var chartdata = mYData[document.getElementById("btn2").value];
// code here that uses chartdata to display the chart
}
I am kind of new in Jquery,and still learning. I am using Chart.Js in order to render data and AJAX calls.
I created a script that update a Radar Chart using a dropdown Button. The goal in mind is:
Each user is part of a team and has some data that I render in a chart. So I there is some fixed data on the chart using a fixed_array and then the user can compare the current member with other member in the team using the drop down button
I managed to do it with static data with that code but I do not know how to make it dynamic.
I imported the whole team data in the form {user_id : [data_array]} for example :
{6: [81, 68, 71, 71, 67, -72], 7: [79, 77, 86, 86, 59, -71], 8: [67, 71, 68, 68, 85, -66]}
and the current_user id with current_user = data.current_user that return the integer of the ID in this situation 6.
I made a try in a separate file in order to test the chart which look like the following:
<script type="text/javascript">
$(document).ready(function () {
// Different arrays for the different data
var array = [];
array["raphael"] = [90, 20, 80, 50, 34];
array["fraxool"] = [89, 12, 68, 89, 90];
array["johnny"] = [78, 89, 1, 90, 80];
// Default value
var fixed_array = [20, 12, 78, 50, 90];
// Chart config
var color = Chart.helpers.color;
var config = {
type: 'radar',
data: {
labels: [["label1"], "label2", "label3", "label4", "label5"],
datasets: [{
label: "Bugsy Bug 1",
backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
data: []
}, {
label: "Bugsy Bug 2",
backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
borderColor: window.chartColors.blue,
pointBackgroundColor: window.chartColors.blue,
data: fixed_array
}]
},
options: {
legend: {
position: 'top',
display: false
},
title: {
display: false,
text: 'Fiverr Chart'
},
scale: {
ticks: {
beginAtZero: true
},
pointLabels: {
fontSize: 10,
lineHeight: 2
}
}
}
};
var mainChart = new Chart(document.getElementById("canvas"), config);
// Event for the select
$(".pick-chart").change(function (e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
config.data.datasets[0].data = array[val];
} else {
config.data.datasets[0].data = [];
}
mainChart.update();
});
});
</script>
But my actual application is getting its data using AJAX:
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels comming from wevsite.views//
info_array = data.info_array
current_user = data.current_user
</script>
right now the output of info_array is {6: [81, 68, 71, 71, 67, -72], 7: [79, 77, 86, 86, 59, -71], 8: [67, 71, 68, 68, 85, -66]}
so {user_id: [data]}
and current_user output : 6
I would like to adapt it to use dynamic data that would adapt to any size of team
Could someone help me to figure it out ?
edited code V2:
<div class="col graph-info">
<div class="card">
<h5 class="card-header text-center bg-dark text-white">Information processing</h5>
<div class="card-body">
<div class="dropdown-container">
<form>
<select id="pick-chart" class="form-control pick-chart">
<option value="0">Compare with</option>
{% for i in team_list_pop %}
<option value="{{i.id}}">{{i.first_name}} {{i.last_name}}</option>
{% endfor %}
</select>
</form>
</div>
<canvas id="info_process"></canvas>
</div>
</div>
<script>
var endpoint = 'api/chart/data'
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels comming from wevsite.views//
complete_label = data.complete_label,
processing_information_label = data.processing_information_label,
motivation_label = data.motivation_label,
action_label = data.action_label,
other_data_label = data.other_data_label,
//Data comming from wevsite.views//
team_name_list2 = data.team_name_list2
info_array = data.info_array
current_user = data.current_user
team_list_id = data.team_list_id
fixed_array = info_array[current_user]
function random_color(){
var color = 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256))+ ',' + 0.2 + ')';
return color
}
//ctx//
var ctx2 = document.getElementById("info_process").getContext('2d');
//graph 2//
var info_process = new Chart(ctx2,{
type: 'radar',
data: {
labels: processing_information_label,
datasets:[{
data: fixed_array, //processing_information_data,
backgroundColor: random_color()
},
{
backgroundColor: random_color(),
data: []
}]
},
options: {
legend: {
position: 'top',
display: false
},
scale: {
display: true,
ticks: {
beginAtZero: true,
}
},
responsive:true,
maintainAspectRatio: true,
}
});
//end graph 2//
$(".pick-chart").change(function (e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels coming from website.views//
info_array = data.info_array
current_user = data.current_user
config.data.datasets[0].data = info_array[val];
config.data.datasets[1].data = info_array[current_user];
mainChart.update();
}
});
} else {
config.data.datasets[0].data = [];
}
mainChart.update();
});
}
})
</script>
If you format your dropdown box as such: (so the user_id in the value of each option)
<select name="pick-chart" class="pick-chart">
<option value="6">Raphael</option>
...
</select>
You could rewrite your pick-chart.change function to something like:
$(".pick-chart").change(function (e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels coming from website.views//
info_array = data.info_array
current_user = data.current_user
config.data.datasets[0].data = info_array[val];
config.data.datasets[1].data = info_array[current_user];
mainChart.update();
}
});
} else {
config.data.datasets[0].data = [];
}
mainChart.update();
});
Assuming your data really is dynamic and could change while the user stays at your page. Also assuming that you want to compare current_user (which should also be a user_id) in dataset 1, like your fixed data, to a selected other user in dataset 0.
I have an angularjs line chart in my page. I am using chart.js as my chart. The data that I have at first is fake and I want to get the true data from the database. I have created a query that can get the date and the total number of members on that specific date. The query goes like this:
SELECT distinct a.time, COUNT(b.member_id) AS Members
FROM b
Inner JOIN a ON b.mir_id = a.mir_id
GROUP BY
a.time order by a.time
And this query returns data like this
I have a line chart code in my controller that goes like this one:
$scope.member;
adminService.getMember()
.then(function(data){
$scope.memberList = data.data.member;
$scope.member = $scope.memberList;
console.log($scope.memberList);
//alert($scope.ptypeList);
//localStorage.ProductType = JSON.stringify(data.data);
$rootScope.loader = false;
});
$scope.percent = 65;
$scope.anotherPercent = -45;
$scope.anotherOptions = {
animate:{
duration:0,
enabled:false
},
barColor:'#2C3E50',
scaleColor:false,
lineWidth:20,
lineCap:'circle'
};
$scope.percent2 = 25;
$scope.anotherPercent2 = -45;
$scope.anotherOptions2 = {
animate:{
duration:0,
enabled:false
},
barColor:'#2C3E50',
scaleColor:false,
lineWidth:20,
lineCap:'circle'
};
$scope.percent3 = 85;
$scope.anotherPercent3 = -45;
$scope.anotherOptions3 = {
animate:{
duration:0,
enabled:false
},
barColor:'#2C3E50',
scaleColor:false,
lineWidth:20,
lineCap:'circle'
};
//--------------
$scope.colors = ['#45b7cd', '#ff6384', '#ff8e72'];
$scope.labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
$scope.data = [
[65, -59, 80, 81, -56, 55, -40],
[28, 48, -40, 19, 86, 27, 90]
];
$scope.datasetOverride = [
{
label: "Bar chart",
borderWidth: 1,
type: 'bar'
},
{
label: "Line chart",
borderWidth: 3,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
type: 'line'
}
];
$scope.labels1 = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
$scope.series1 = ['Series A', 'Series B'];
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
$scope.datasetOverride1 = [{ yAxisID: 'y-axis-1' }];
$scope.options1 = {
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left',
data: $scope.member
},
]
}
}
I am quite confused on how can I assign the values I get from the database to the line chart. How can I do that?
First you should aggregate your data returned from the database.Use the SUM() function.The correct format should be this:
Date | Member
-------------------
2016-06-23 | 5
2016-06-24 | 10
In the controller you should have an array.
data = [{Date:"2016-0-23",Member:5},{Date:"2016-06-24",Member:10}];
To create a simple chart you need the data and labels.
vm.labels = data.map(function (property) {return propery.Date;});
vm.data = data.map(function (property) {return propery.Member;});
On the HTML page:
<canvas id="line" class="chart chart-line" chart-data="vm.data" chart-labels="vm.labels"></canvas>