如何在堆叠条形图中为每个日期范围显示多个堆叠列 [英] How do I display multiple stacked columns for each date range in an stacked Bar

查看:186
本文介绍了如何在堆叠条形图中为每个日期范围显示多个堆叠列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,目的是比较我的团队中每个成员每周执行的任务类别。



我想添加周数在Axes下面而不是1.0,2.0和3.0。



我得到错误的结果,因为它只显示1为优秀和所有week1,week2,week3,week4



我从2014年1月12日开始选择,结束日期是2014年12月31日,所以我期待有1个用于坏,2个用于良好,3个用于优秀。





这是我的PHP代码

 <?php> 
$ result = mysqli_query($ con,SELECT * FROM`constry` WHERE`Bate` BETWEEN'。$ _POST
['start']。'AND'。$ _POST ['end ']。'或死(错误:。mysqli_error($ con));

$ Levels = 0;
$ Levelscounter = 0;
$ countergood = 0;
$ counterbad = 0;
while($ row = mysqli_fetch_array($ result))
{
$ answer = $ row ['level'];


$ bad ='bad';
$ good ='good';
$ excellent ='excellent';
if($ answer == $ bad)

{
$ counterbad ++;
}
if($ answer == $ good)
{
$ countergood ++;
}
if($ answer == $ excellent)
{
$ counterexcellent ++;
}
$ Levelscounter;
}
mysqli_close($ con);
?>

这是我的JavaScript代码:

 < script type =text / javascript> 
(函数($){
var series = [{
data:[[1,<?php echo $ counterbad;?>]],
valueLabels:{
显示:true,
valign:'中'
},
标签:低
},
{
数据:[ [1,<?php echo $ countergood;?>]],
valueLabels:{
show:true,
valign:'middle'
},

标签:中
},{
数据:[[1,<?php echo $ counterexcellent;?>]],
valueLabels:{
show:true,
valign:'middle'
},
label:High
}];

var options = {
x轴:{
minTickSize:1
},
系列:{
bars:{
show:true,
barWidth:.8,
align:center
},
stack:true
}
};

$ .plot(#placeholder,系列,选项);
})(jQuery);
< / script>

我得到堆积图表中显示的水平,从开始和结束日期开始工作正常我选择但我可以将此结果显示为每周结果。
我想知道我需要添加什么?有什么想法吗?
PHP中是否有一个功能可以解决这个问题?



谢谢。



更新



正如你在每个系列的图片编号中看到的那样,与坏,好,优秀有关。
红色为坏,有利于蓝色和黄色为优秀。

解决方案

添加计算出现次数并构建
图表列。



我使用函数简化了代码,以便于您使用

 <?php 
$ con = mysqli_connect(localhost,root,','你的数据库');

函数getChartData($ con,$ startDate,$ endDate){

$ startDate = date(Y-m-d H:i:s,strtotime($ startDate));
$ endDate = date(Y-m-d H:i:s,strtotime($ endDate));

$ query =SELECT * FROM`sofers` WHERE`date` BETWEEN'$ startDate'和'$ endDate';

$ result = mysqli_query($ con,$ query)或die(Error:。mysqli_error($ con));

//一个多维数组,每周包含
$ weeksData = [];

//每周用它的数据分组
while($ row = mysqli_fetch_array($ result)){
$ weekNumber = date(W,strtotime($ row [ '日期']));
if(isset($ weeksData [$ weekNumber]))
{
$ weeksData [$ weekNumber] [] = $ row ['level'];
}
$ weeksData [$ weekNumber] [] = $ row ['level'];
}

//重置数组索引并对数组进行排序
sort($ weeksData);

$ data = array();

//使用array_count_values来计算(好的,坏的和优秀的)
foreach的数量($ weekData as $ key => $ week){
$ data [$ key] = array_count_values($ week);
}

//返回所有周数(好的,坏的和优秀的)出现
返回$ data;
}

//构建javascript对象{data:['week num',occuerences]}
函数buildColumn($ data,$ label,$ numberOfWeeks)
{
$ data = array_column($ data,strtolower($ label));
$ balance = $ numberOfWeeks - count($ data);
if($ balance!= 0){
for($ i = 1; $ i< = $ balance; $ i ++){
$ data [] = 1;
}
}

$ string ='{data:[';
foreach($ data as $ key => $ value){
$ weekNumber = $ key + 1;
$ string。='[Week'。$ weekNumber。','。$ value。'],';
}
$ string = rtrim($ string,',');
$ string。=],valueLabels:{show:true,valign:'middle'},label:'$ label'};
返回$ string;
}

函数getNumberofWeeks($ startDate,$ endDate){
$ weeks = array();
$ period = new DatePeriod(new DateTime($ startDate),
DateInterval :: createFromDateString('+ 1 day'),new DateTime($ endDate)
);
foreach($ period as $ dt){
$ weeks [] = $ dt-> format('W');
}
返回计数(array_unique($ weeks));
}

现在您可以轻松使用这些功能

  $ numberOfWeeks = getNumberofWeeks($ _ POST ['start'],$ _ POST ['end']); 

//获取最后一周的数据
$ chartData = getChartData($ con,$ _POST ['start'],$ _ POST ['end']);
//为每次出现建立列数据
$ badColumn = buildColumn($ chartData,'Bad',$ numberOfWeeks);
$ goodColumn = buildColumn($ chartData,'Good',$ numberOfWeeks);
$ excellentColumn = buildColumn($ chartData,'Excellent',$ numberOfWeeks);

//输出{data:...},{data:...},{data:....}
$ output =$ excellentColumn,$ goodColumn,$ badColumn;



完整的工作示例



 <!DOCTYPE html> 
< html>
< head>
< title>< / title>
< script src =// ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>
< script src =jquery.flot.min.js>< / script>
< script src =jquery.flot.categories.min.js>< / script>
< script src =jquery.flot.stack.min.js>< / script>
< / head>
< body>
<?php
$ con = mysqli_connect(localhost,root,','你的数据库');

函数getChartData($ con,$ startDate,$ endDate){

$ startDate = date(Y-m-d H:i:s,strtotime($ startDate));
$ endDate = date(Y-m-d H:i:s,strtotime($ endDate));

$ query =SELECT * FROM`sofers` WHERE`date` BETWEEN'$ startDate'和'$ endDate';

$ result = mysqli_query($ con,$ query)或die(Error:。mysqli_error($ con));

//一个多维数组,每周包含
$ weeksData = [];

//每周用它的数据分组
while($ row = mysqli_fetch_array($ result)){
$ weekNumber = date(W,strtotime($ row [ '日期']));
if(isset($ weeksData [$ weekNumber]))
{
$ weeksData [$ weekNumber] [] = $ row ['level'];
}
$ weeksData [$ weekNumber] [] = $ row ['level'];
}

//重置数组索引并对数组进行排序
sort($ weeksData);

$ data = array();

//使用array_count_values来计算(好的,坏的和优秀的)
foreach的数量($ weekData as $ key => $ week){
$ data [$ key] = array_count_values($ week);
}

//返回所有周数(好的,坏的和优秀的)出现
返回$ data;
}

//构建javascript对象{data:['week num',occuerences]}
函数buildColumn($ data,$ label,$ numberOfWeeks)
{
$ data = array_column($ data,strtolower($ label));
$ balance = $ numberOfWeeks - count($ data);
if($ balance!= 0){
for($ i = 1; $ i< = $ balance; $ i ++){
$ data [] = 1;
}
}

$ string ='{data:[';
foreach($ data as $ key => $ value){
$ weekNumber = $ key + 1;
$ string。='[Week'。$ weekNumber。','。$ value。'],';
}
$ string = rtrim($ string,',');
$ string。=],valueLabels:{show:true,valign:'middle'},label:'$ label'};
返回$ string;
}

函数getNumberofWeeks($ startDate,$ endDate){
$ weeks = array();
$ period = new DatePeriod(new DateTime($ startDate),
DateInterval :: createFromDateString('+ 1 day'),new DateTime($ endDate)
);
foreach($ period as $ dt){
$ weeks [] = $ dt-> format('W');
}
返回计数(array_unique($ weeks));
}
//你想在图表中显示的周数
$ numberOfWeeks = getNumberofWeeks($ _ POST ['start'],$ _ POST ['end']);

//获取最后一周的数据
$ chartData = getChartData($ con,$ _POST ['start'],$ _ POST ['end']);
//为每次出现建立列数据
$ badColumn = buildColumn($ chartData,'Bad',$ numberOfWeeks);
$ goodColumn = buildColumn($ chartData,'Good',$ numberOfWeeks);
$ excellentColumn = buildColumn($ chartData,'Excellent',$ numberOfWeeks);

//输出{data:...},{data:...},{data:....}
$ output =$ excellentColumn,$ goodColumn,$ badColumn;

?>
< div id =placeholderstyle =width:818px; height:413px>< / div>
< script type =text / javascript>
$(function(){
var series = [<?php echo $ output;?>];
$ .plot(#placeholder,series,{
系列:{
stack:true,
lines:{fill:true,show:false,steps:false},
bars:{
show:true,
barWidth:0.8,
align:middle,
},
},
xaxis:{
mode:categories,
minTickSize: 1
}
});
});
< / script>
< / body>
< / html>



编辑



只需更换这两个功能使其兼容 dd / mm / yyyy

  function getChartData( $ con,$ startDate,$ endDate){
$ startDate = explode('/',$ startDate);
$ startDate = $ startDate [1]。 '/'。 $ startDate [0]。 '/'。 $的startDate [2];

$ endDate = explode('/',$ endDate);
$ endDate = $ endDate [1]。 '/'。 $ endDate [0]。 '/'。 $结束日期[2];

$ startDate = date(Y-m-d H:i:s,strtotime($ startDate));
$ endDate = date(Y-m-d H:i:s,strtotime($ endDate));

$ query =SELECT * FROM`sofers` WHERE`date` BETWEEN'$ startDate'和'$ endDate';

$ result = mysqli_query($ con,$ query)或die(Error:。mysqli_error($ con));

//一个多维数组,每周包含
$ weeksData = [];

//每周用它的数据分组
while($ row = mysqli_fetch_array($ result)){
$ weekNumber = date(W,strtotime($ row [ '日期']));
if(isset($ weeksData [$ weekNumber]))
{
$ weeksData [$ weekNumber] [] = $ row ['level'];
}
$ weeksData [$ weekNumber] [] = $ row ['level'];
}

//重置数组索引并对数组进行排序
sort($ weeksData);

$ data = array();

//使用array_count_values来计算(好的,坏的和优秀的)
foreach的数量($ weekData as $ key => $ week){
$ data [$ key] = array_count_values($ week);
}

//返回所有周数(好的,坏的和优秀的)出现
返回$ data;
}

  function getNumberofWeeks($ startDate,$ endDate){
$ startDate = explode('/',$ startDate);
$ startDate = $ startDate [1]。 '/'。 $ startDate [0]。 '/'。 $的startDate [2];

$ endDate = explode('/',$ endDate);
$ endDate = $ endDate [1]。 '/'。 $ endDate [0]。 '/'。 $结束日期[2];
$ diff = strtotime($ startDate,0) - strtotime($ endDate,0);

返回str_replace(' - ','',(int)floor($ diff / 604800));
}


Essentially, the purpose is to compare what categories of tasks each member on my team is performing on a weekly basis.

and I would like to add number of Week underneath the Axes instead of 1.0 , 2.0 and 3.0 .

I am getting wrong result as its only showing 1 for excellent and for all week1, week2, week3, week4

I selected starting day 1/12/2014 and the end date is 31/12/2014 so I was expecting to have 1 for bad and two for good and three for excellent.

This is my PHP code

<?php>
$result = mysqli_query($con,"SELECT * FROM `employees` WHERE  `Date` BETWEEN  '" . $_POST     
['start'] . "' AND  '" . $_POST ['end'] . "' ") or die ("Error: ".mysqli_error($con));

$Levels = 0;
        $Levelscounter=0;
        $countergood=0;
        $counterbad=0;
        while($row = mysqli_fetch_array($result))
         {
            $answer = $row['level'];


                 $bad = 'bad';
                 $good='good';
                 $excellent='excellent';
                  if ($answer == $bad)

             {
                $counterbad++;
             }
             if($answer == $good)
             {
               $countergood++;
             }
             if($answer == $excellent)
             {
               $counterexcellent++;
             }
             $Levelscounter;
                        }
             mysqli_close($con); 
        ?>

Here is my JavaScript Code:

       <script type="text/javascript">
         (function($) {
          var series = [{
          data: [[ 1,<?php echo $counterbad; ?>] ],
               valueLabels: {
               show: true,
               valign: 'middle'
                }     ,
         label: "Low"
         },
         {
       data: [[1,<?php echo $countergood; ?>]], 
           valueLabels: {
    show: true,
    valign: 'middle'
}     ,

    label: "Medium"
   }, {
    data: [[1,<?php echo $counterexcellent; ?>]],
     valueLabels: {
    show: true,
    valign: 'middle'
   }     ,
    label: "High"
   }];

    var options = {
    xaxis: {
        minTickSize: 1
    },
    series: {
        bars: {
            show: true,
            barWidth: .8,
            align: "center"
        },
        stack: true
    }
   };

  $.plot("#placeholder", series, options);
  })(jQuery);
 </script>

I got the levels displayed in the stacked chart and it is working fine regarding from the start and end date I select but I could display this result as a weekly result. I would like to get ideas what do I need to add ? Any ideas please ? Is there a function in PHP that sort out this ?

Thank you.

Updating

As you can see in the image numbers on each series related to bad, good, excellent. red for bad and good for blue and yellow for excellent.

解决方案

To add weeks/textual data underneath the columns you have to add the library's categories file jquery.flot.categories.min.js to your javascript assets.

If i understand you correctly you want the chart to look like this

Javascript

You need to add these files in

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jquery.flot.min.js"></script>
<script src="jquery.flot.categories.min.js"></script>
<script src="jquery.flot.stack.min.js"></script>

and initialize the library we will talk about $output after this code

<div id="placeholder" style="width:818px;height:413px" ></div>
<script type="text/javascript">
$(function() {
    var series = [<?php echo $output; ?>];
       $.plot("#placeholder", series, {
        series: {
            stack:true,
            lines:{fill:true,show:false,steps:false},
            bars: {
                show: true,
                barWidth: 0.8,
                align: "middle",
            },
        },
        xaxis: {
            mode: "categories",
            minTickSize: 1
        }
       });
});

PHP

First you need to query the database to find the date between the specified dates, after getting the result you have to sort the data for each week in an array

For instance week One => 'good','good','bad','bad', 'week two' => and so on ...

after that you can use array_count_values() to count the number of occurrences and build the charts column.

I simplified the code using functions to make it easier for you

<?php
$con = mysqli_connect("localhost", 'root','','your db');

function getChartData($con, $startDate, $endDate){

    $startDate = date("Y-m-d H:i:s", strtotime($startDate));
    $endDate = date("Y-m-d H:i:s", strtotime($endDate));

    $query = "SELECT * FROM `employees` WHERE `date` BETWEEN '$startDate' AND '$endDate'";

    $result = mysqli_query($con, $query) or die ("Error: ".mysqli_error($con));

    // a multidimenional array containing each week with it's
    $weeksData = [];

    // Group each week with it's data 
    while($row = mysqli_fetch_array($result)){
        $weekNumber = date("W", strtotime($row['date']));
        if(isset($weeksData[$weekNumber]))
        {
            $weeksData[$weekNumber][] = $row['level'];
        }
        $weeksData[$weekNumber][] = $row['level'];
    }

    // reset array indexes and sort the array
    sort($weeksData);

    $data = array();

    // using array_count_values to count the number of (good, bad and excellent)
    foreach ($weeksData as $key => $week) {
        $data[$key] = array_count_values($week);
    }

    // return all the weeks with number of (good, bad and excellent) occurences 
    return $data;
}

// build the javascript object {data:['week num', occuerences]}
function buildColumn($data,$label, $numberOfWeeks)
{
    $data = array_column($data,strtolower($label));
    $balance = $numberOfWeeks - count($data);
    if($balance !=0){ 
        for($i=1;$i<=$balance;$i++) { 
            $data[] = 1; 
        } 
    }

    $string = '{data: [';
    foreach ($data as $key => $value) {
        $weekNumber = $key+1;
        $string .= '["Week '.$weekNumber.'",'.$value.'],';
    }
    $string = rtrim($string, ',');
    $string .= "],valueLabels: {show: true,valign: 'middle'},label: '$label'}";
    return $string;
}

function getNumberofWeeks($startDate, $endDate){
      $weeks = array();
      $period = new DatePeriod(new DateTime($startDate),
        DateInterval::createFromDateString('+1 day'),new DateTime($endDate) 
      );
      foreach ( $period as $dt ) {
        $weeks[] = $dt->format( 'W' );
      }
      return count(array_unique($weeks));
}  

now you can easily use these functions like this

$numberOfWeeks = getNumberofWeeks($_POST['start'],$_POST['end']);

// get data of the last number of weeks
$chartData = getChartData($con, $_POST['start'],$_POST['end']);
// bulding columns data for each occurence
$badColumn = buildColumn($chartData,'Bad', $numberOfWeeks);
$goodColumn = buildColumn($chartData,'Good', $numberOfWeeks);
$excellentColumn = buildColumn($chartData,'Excellent', $numberOfWeeks);

// output {data: ...}, {data: ...},{data:....}
$output = "$excellentColumn , $goodColumn , $badColumn";  

Full working Example

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="jquery.flot.min.js"></script>
    <script src="jquery.flot.categories.min.js"></script>
    <script src="jquery.flot.stack.min.js"></script>
</head>
<body>
<?php
$con = mysqli_connect("localhost", 'root','','your db');

function getChartData($con, $startDate, $endDate){

    $startDate = date("Y-m-d H:i:s", strtotime($startDate));
    $endDate = date("Y-m-d H:i:s", strtotime($endDate));

    $query = "SELECT * FROM `employees` WHERE `date` BETWEEN '$startDate' AND '$endDate'";

    $result = mysqli_query($con, $query) or die ("Error: ".mysqli_error($con));

    // a multidimenional array containing each week with it's
    $weeksData = [];

    // Group each week with it's data 
    while($row = mysqli_fetch_array($result)){
        $weekNumber = date("W", strtotime($row['date']));
        if(isset($weeksData[$weekNumber]))
        {
            $weeksData[$weekNumber][] = $row['level'];
        }
        $weeksData[$weekNumber][] = $row['level'];
    }

    // reset array indexes and sort the array
    sort($weeksData);

    $data = array();

    // using array_count_values to count the number of (good, bad and excellent)
    foreach ($weeksData as $key => $week) {
        $data[$key] = array_count_values($week);
    }

    // return all the weeks with number of (good, bad and excellent) occurences 
    return $data;
}

// build the javascript object {data:['week num', occuerences]}
function buildColumn($data,$label, $numberOfWeeks)
{
    $data = array_column($data,strtolower($label));
    $balance = $numberOfWeeks - count($data);
    if($balance !=0){ 
        for($i=1;$i<=$balance;$i++) { 
            $data[] = 1; 
        } 
    }

    $string = '{data: [';
    foreach ($data as $key => $value) {
        $weekNumber = $key+1;
        $string .= '["Week '.$weekNumber.'",'.$value.'],';
    }
    $string = rtrim($string, ',');
    $string .= "],valueLabels: {show: true,valign: 'middle'},label: '$label'}";
    return $string;
}

function getNumberofWeeks($startDate, $endDate){
      $weeks = array();
      $period = new DatePeriod(new DateTime($startDate),
        DateInterval::createFromDateString('+1 day'),new DateTime($endDate) 
      );
      foreach ( $period as $dt ) {
        $weeks[] = $dt->format( 'W' );
      }
      return count(array_unique($weeks));
}
// the number of weeks that you want to display in the chart
$numberOfWeeks = getNumberofWeeks($_POST['start'],$_POST['end']);

// get data of the last number of weeks
$chartData = getChartData($con, $_POST['start'],$_POST['end']);
// bulding columns data for each occurence
$badColumn = buildColumn($chartData,'Bad', $numberOfWeeks);
$goodColumn = buildColumn($chartData,'Good', $numberOfWeeks);
$excellentColumn = buildColumn($chartData,'Excellent', $numberOfWeeks);

// output {data: ...}, {data: ...},{data:....}
$output = "$excellentColumn , $goodColumn , $badColumn";

?>
<div id="placeholder" style="width:818px;height:413px" ></div>
<script type="text/javascript">
$(function() {
    var series = [<?php echo $output; ?>];
       $.plot("#placeholder", series, {
        series: {
            stack:true,
            lines:{fill:true,show:false,steps:false},
            bars: {
                show: true,
                barWidth: 0.8,
                align: "middle",
            },
        },
        xaxis: {
            mode: "categories",
            minTickSize: 1
        }
       });
});
  </script>
 </body>
</html> 

Edit

Just replace these two functions to make it compatible with dd/mm/yyyy

 function getChartData($con, $startDate, $endDate){
    $startDate = explode('/', $startDate);
    $startDate = $startDate[1] . '/' . $startDate[0] . '/' . $startDate[2];

    $endDate = explode('/', $endDate);
    $endDate = $endDate[1] . '/' . $endDate[0] . '/' . $endDate[2];

    $startDate = date("Y-m-d H:i:s", strtotime($startDate));
    $endDate = date("Y-m-d H:i:s", strtotime($endDate));

    $query = "SELECT * FROM `employees` WHERE `date` BETWEEN '$startDate' AND '$endDate'";

    $result = mysqli_query($con, $query) or die ("Error: ".mysqli_error($con));

    // a multidimenional array containing each week with it's
    $weeksData = [];

    // Group each week with it's data 
    while($row = mysqli_fetch_array($result)){
        $weekNumber = date("W", strtotime($row['date']));
        if(isset($weeksData[$weekNumber]))
        {
            $weeksData[$weekNumber][] = $row['level'];
        }
        $weeksData[$weekNumber][] = $row['level'];
    }

    // reset array indexes and sort the array
    sort($weeksData);

    $data = array();

    // using array_count_values to count the number of (good, bad and excellent)
    foreach ($weeksData as $key => $week) {
        $data[$key] = array_count_values($week);
    }

    // return all the weeks with number of (good, bad and excellent) occurences 
    return $data;
}

and

   function getNumberofWeeks($startDate, $endDate){
    $startDate = explode('/', $startDate);
    $startDate = $startDate[1] . '/' . $startDate[0] . '/' . $startDate[2];

    $endDate = explode('/', $endDate);
    $endDate = $endDate[1] . '/' . $endDate[0] . '/' . $endDate[2];
    $diff = strtotime($startDate, 0) - strtotime($endDate, 0);

    return str_replace('-','', (int)floor($diff / 604800));
}

这篇关于如何在堆叠条形图中为每个日期范围显示多个堆叠列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆