javascript - 在同一页面上创建钻取融合图表

标签 javascript php fusioncharts

如果您搜索我所询问的内容,您将在 fusioncharts 网站上得到结果,但这并不是我正在寻找的内容。

我正在从 MySQL 数据库查询数据,并将这些数据放入融合图表中以显示在我的网页上。我希望同一页面上有 2 个图表,当您单击父图表上的其中一个数据点时,子图表将显示“向下钻取”图表。我怎样才能做到这一点?截至目前,我可以按父图,它将在新网页上打开子图。这是带有父图的主页的代码。该文件名为“dept.php”。

<?php

/*Include the `fusioncharts.php` file that contains functions
        to embed the charts.
*/
  include("includes/fusioncharts.php");

 // Establish a connection to the database. Variables defined before
 $dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);

 // Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect
 if ($dbhandle->connect_error) {
      exit("There was an error with your connection: ".$dbhandle->connect_error);
 }

?>

<html>
   <head>
        <title>FusionCharts XT - Column 2D Chart - Data from a database</title>
          <link  rel="stylesheet" type="text/css" href="css/style.css" />

        <!--  Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->

      <script src="fusioncharts/js/fusioncharts.js"></script>
   </head>
   <body>
        <?php

        // Form the SQL query that returns the top 10 most populous countries
        $strQuery = "SELECT Department, SUM(Quantity) AS Quantity FROM Scrap GROUP BY Department ORDER BY Department";

        // Execute the query, or else return the error message.
        $result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");

        // If the query returns a valid response, prepare the JSON string
        if ($result) {
                // The `$arrData` array holds the chart attributes and data
                $arrData = array(
                "chart" => array(
                    "caption" => "Sample Chart",
                    "paletteColors" => "#0075c2",
                    "bgColor" => "#ffffff",
                    "borderAlpha"=> "20",
                    "canvasBorderAlpha"=> "0",
                    "usePlotGradientColor"=> "0",
                    "plotBorderAlpha"=> "10",
                    "showXAxisLine"=> "1",
                    "xAxisLineColor" => "#999999",
                    "showValues"=> "0",
                    "divlineColor" => "#999999",
                    "divLineIsDashed" => "1",
                    "showAlternateHGridColor" => "0"
                )
                );

                $arrData["data"] = array();

        // Push the data into the array

                while($row = mysqli_fetch_array($result)) {
                array_push($arrData["data"], array(
                "label" => $row["Department"],
                "value" => $row["Quantity"],
                "link" => "deptDrillDown.php?Department=".$row["Department"]
                )
                );
                }

                /*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */

                $jsonEncodedData = json_encode($arrData);

                /*Create an object for the column chart. Initialize this object using the FusionCharts PHP class constructor. The constructor is used to initialize
                 the chart type, chart id, width, height, the div id of the chart container, the data format, and the data source. */

                $columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);

                // Render the chart
                $columnChart->render();

                // Close the database connection
                $dbhandle->close();

        }

        ?>
        <div id="chart-1"><!-- Fusion Charts will render here--></div>
   </body>
</html>

然后这是包含子图的另一个页面。该文件名为“deptDrillDown.php”。

<?php

 /* Include the `includes/fusioncharts.php` file that contains functions to embed the charts.*/

   include("includes/fusioncharts.php");

   // Establish a connection to the database. Variables defined earlier
   $dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);

  /*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
   if ($dbhandle->connect_error) {
        exit("There was an error with your connection: ".$dbhandle->connect_error);
   }
?>
<html>
   <head>
        <title>FusionCharts XT - Column 2D Chart</title>
        <link  rel="stylesheet" type="text/css" href="css/style.css" />

          <!--  Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->

        <script src="fusioncharts/js/fusioncharts.js"></script>
   </head>
   <body>
        <?php

        // Get the country code from the GET parameter
        $countryCode = $_GET["Department"];

        // Form the SQL query that returns the top 10 most populous cities in the selected country
        $cityQuery = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = ? GROUP BY ScrapDate ORDER BY ScrapDate";

        // Prepare the query statement
        $cityPrepStmt = $dbhandle->prepare($cityQuery);

        // If there is an error in the statement, exit with an error message
        if($cityPrepStmt === false) {
                exit("Error while preparing the query to fetch data from City Table. ".$dbhandle->error);
        }

        // Bind the parameters to the query prepared
        $cityPrepStmt->bind_param("s", $countryCode);

        // Execute the query
        $cityPrepStmt->execute();

        // Get the results from the query executed
        $cityResult = $cityPrepStmt->get_result();

        // If the query returns a valid response, prepare the JSON string
        if ($cityResult) {

                /* Form the SQL query that will return the country name based on the country code. The result of the above query contains only the country code.
                The country name is needed to be rendered as a caption for the chart that shows the 10 most populous cities */

                $countryNameQuery = "SELECT ScrapDate FROM Scrap WHERE Department = ?";

                // Prepare the query statement
                $countryPrepStmt = $dbhandle->prepare($countryNameQuery);

                // If there is an error in the statement, exit with an error message
                if($countryPrepStmt === false) {
                exit("Error while preparing the query to fetch data from Country Table. ".$dbhandle->error);
                }

                // Bind the parameters to the query prepared
                $countryPrepStmt->bind_param("s", $countryCode);

                // Execute the query
                $countryPrepStmt->execute();

                // Bind the country name to the variable `$countryName`
                $countryPrepStmt->bind_result($countryName);

                // Fetch the result from prepared statement
                $countryPrepStmt->fetch();
                // The `$arrData` array holds the chart attributes and data
                $arrData = array(
                "chart" => array(
                    "caption" => "Top 10 Most Populous Cities in ".$countryName,
                    "paletteColors" => "#0075c2",
                    "bgColor" => "#ffffff",
                    "borderAlpha"=> "20",
                    "canvasBorderAlpha"=> "0",
                    "usePlotGradientColor"=> "0",
                    "plotBorderAlpha"=> "10",
                    "showXAxisLine"=> "1",
                    "xAxisLineColor" => "#999999",
                    "showValues"=> "0",
                    "divlineColor" => "#999999",
                    "divLineIsDashed" => "1",
                    "showAlternateHGridColor" => "0"
                )
                );

                $arrData["data"] = array();

        // Push the data into the array
                while($row = $cityResult->fetch_array()) {
                array_push($arrData["data"], array(
                "label" => $row["ScrapDate"],
                "value" => $row["Quantity"]
                )
                );
                }

           /*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */

                $jsonEncodedData = json_encode($arrData);

          /*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is `FusionCharts("type of chart",
                 "unique chart id", "width of chart", "height of chart", "div id to render the chart", "data format", "data source")`.*/

                $columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);

                // Render the chart
                $columnChart->render();

                // Close the database connection
                $dbhandle->close();
        }
        ?>

        <a href="dept.php">Back</a>
        <div id="chart-1"><!-- Fusion Charts will render here--></div>
   </body>
</html>

最佳答案

  • 使用 FusionCharts 可以在单个页面中呈现n 个图表。
  • 存储他们的图表引用,例如在关联数组中。
  • 使用dataplotClick event 来捕获通过单击数据生成的事件。
  • 在回调中,使用 setJSONData要更新子图表,需要更新。

一个虚拟代码是:

FusionCharts.ready(function () {
var chart1 = new FusionCharts({
    type: 'msstackedcolumn2d',
    renderAt: 'chart-container1',
    width: '550',
    height: '350',
    dataFormat: 'json',
    dataSource: {
       // enter the json data here
    },
    "events": {
        "dataplotClick": function(eventObj, dataObj) {
             /* so every time a dataClickEvent is being triggered from the data plot,
                a new json `json2` is fetched from a sql query and
                chart2 is updated with it.*/
             chart2.setJSONData(json2);
        }
    }
} 
}).render();    
});

几天前我创建了这个 fiddle ,希望这在这里也有用。这里我们没有执行 SQL 查询,而是有一个通用数据,每次单击时,它都会在内部进行函数调用,并从中动态创建数据。为了使其完全动态而进行的大量函数调用可能会使代码看起来很复杂。但我在虚拟代码 avobe 中分享的基本理念在这里是相同的。

用于快速引用的代码片段版本。最好在整页中运行结果以检查到底发生了什么。

function getData() {

  var arr = [{
    seriesname: "Book A",
    data: [{
      "label": "Paper",
      "value": 100
    }, {
      "label": "Promotion",
      "value": 150
    }, {
      "label": "Transportation",
      "value": 175
    }, {
      "label": "Royality",
      "value": 200
    }, {
      "label": "Printing",
      "value": 250
    }, {
      "label": "Binding",
      "value": 275
    }]
  }, {
    seriesname: "Book B",
    data: [{
      "label": "Paper",
      "value": 130
    }, {
      "label": "Promotion",
      "value": 110
    }, {
      "label": "Transportation",
      "value": 155
    }, {
      "label": "Royality",
      "value": 250
    }, {
      "label": "Printing",
      "value": 210
    }, {
      "label": "Binding",
      "value": 215
    }]
  }, {
    seriesname: "Book C",
    data: [{
      "label": "Paper",
      "value": 70
    }, {
      "label": "Promotion",
      "value": 180
    }, {
      "label": "Transportation",
      "value": 125
    }, {
      "label": "Royality",
      "value": 150
    }, {
      "label": "Printing",
      "value": 290
    }, {
      "label": "Binding",
      "value": 245
    }]
  }, {
    seriesname: "Book D",
    data: [{
      "label": "Paper",
      "value": 150
    }, {
      "label": "Promotion",
      "value": 100
    }, {
      "label": "Transportation",
      "value": 105
    }, {
      "label": "Royality",
      "value": 125
    }, {
      "label": "Printing",
      "value": 278
    }, {
      "label": "Binding",
      "value": 235
    }]
  }, {
    seriesname: "Book E",
    data: [{
      "label": "Paper",
      "value": 60
    }, {
      "label": "Promotion",
      "value": 250
    }, {
      "label": "Transportation",
      "value": 115
    }, {
      "label": "Royality",
      "value": 189
    }, {
      "label": "Printing",
      "value": 190
    }, {
      "label": "Binding",
      "value": 285
    }]
  }, {
    seriesname: "Book F",
    data: [{
      "label": "Paper",
      "value": 190
    }, {
      "label": "Promotion",
      "value": 200
    }, {
      "label": "Transportation",
      "value": 160
    }, {
      "label": "Royality",
      "value": 148
    }, {
      "label": "Printing",
      "value": 178
    }, {
      "label": "Binding",
      "value": 295
    }]
  }];

  return arr;
}

function getValues(componentName) {
  var i,
    j,
    arr = getData(),
    valueArr = [],
    len1;
  for (i = 0, len = arr.length; i < len; i += 1) {
    for (j = 0, len1 = arr[i].data.length; j < len1; j += 1) {
      if (arr[i].data[j].label === componentName) {
        valueArr.push({
          value: arr[i].data[j].value
        });
        break;
      }
    }
  }
  return [{
    seriesname: componentName,
    data: valueArr
  }];
}

function getProducts(componentName) {
  var arr = getData(),
    productArr = [];
  for (i = 0, len = arr.length; i < len; i += 1) {
    for (j = 0; j < arr[i].data.length; j += 1) {
      if (arr[i].data[j].label === componentName) {
        productArr.push({
          "label": arr[i].seriesname,
          "value": arr[i].data[j].value
        });
        break;
      }
    }
  }
  return productArr;
}

function getComponents(label, value) {
  var arr = getData(),
    sum,
    i,
    j,
    len,
    len1,
    obj =
    componentArr = [];
  if (label === undefined) {
    label = true;
  }
  if (value === undefined) {
    value = true;
  }
  for (i = 0, len = arr[0].data.length; i < len; i += 1) {
    sum = 0;
    obj = {};
    for (j = 0, len1 = arr.length; j < len1; j += 1) {
      sum += arr[j].data[i].value;
    }
    if (label) {
      obj.label = arr[0].data[i].label;
    }
    if (value) {
      obj.value = sum;
    }
    componentArr.push(obj);
  }
  return componentArr;
}

function getSeriesNames() {
  var arr = getData(),
    seriesName = [];
  for (i = 0, len = arr.length; i < len; i += 1) {
    seriesName.push({
      "label": arr[i].seriesname
    });
  }
  return seriesName;
}

function getMode() {
  var e = document.getElementById("interaction");
  return e.options[e.selectedIndex].value;
}

FusionCharts.ready(function() {
  var lastClickedId = true;

  var pieChart = new FusionCharts({
    type: 'pie2d',
    renderAt: 'pieContainer',
    width: '600',
    height: '400',
    dataFormat: 'json',
    dataSource: {
      "chart": {
        "caption": "Expenditures Incurred in Publishing a Book",
        "subCaption": "Component-wise BreakUp",
        "enableMultiSlicing": "0",
        "bgcolor": "FFFFFF",
        "showvalues": "1",
        "showpercentvalues": "1",
        "showborder": "0",
        "showplotborder": "0",
        "showlegend": "1",
        "legendborder": "0",
        "legendposition": "bottom",
        "enablesmartlabels": "1",
        "use3dlighting": "0",
        "showshadow": "0",
        "legendbgcolor": "#CCCCCC",
        "legendbgalpha": "20",
        "legendborderalpha": "0",
        "legendshadow": "0",
        "legendnumcolumns": "3",
        "palettecolors": "#f8bd19,#e44a00,#008ee4,#33bdda,#6baa01,#583e78"
      },
      "data": getComponents()
    },
    "events": {
      "dataplotClick": function(eventObj, dataObj) {
        if (getMode() === 'pie') {
          var json = stackedChart.getJSONData(),
            categoryLabel = dataObj.categoryLabel;
          json.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
          json.categories[0].category = getSeriesNames();
          json.dataset = getValues(dataObj.categoryLabel);
          stackedChart.setJSONData(json);
        }
      }
    }
  }).render();

  var stackedChart = new FusionCharts({
    type: 'stackedBar2D',
    renderAt: 'barContainer',
    width: '600',
    height: '400',
    dataFormat: 'json',
    dataSource: {
      "chart": {
        "bgcolor": "FFFFFF",
        "outcnvbasefontcolor": "666666",
        "caption": "Expenditures Incurred in Publishing a Book",
        "subCaption": "Product-wise BreakUp",
        "xaxisname": "Expenditures Cost",
        "yaxisname": "Cost",
        "numberprefix": "$",
        "showvalues": "0",
        "numvdivlines": "10",
        "showalternatevgridcolor": "1",
        "alternatevgridcolor": "e1f5ff",
        "divlinecolor": "e1f5ff",
        "vdivlinecolor": "e1f5ff",
        "basefontcolor": "666666",
        "tooltipbgcolor": "F3F3F3",
        "tooltipbordercolor": "666666",
        "canvasbordercolor": "666666",
        "canvasborderthickness": "1",
        "showplotborder": "1",
        "plotfillalpha": "80",
        "showborder": "0",
        "legendbgcolor": "#CCCCCC",
        "legendbgalpha": "20",
        "legendborderalpha": "0",
        "legendshadow": "0",
        "legendnumcolumns": "3"
      },
      "categories": [{
        "category": getComponents(true, false)
      }],
      "dataset": getData()
    },
    "events": {
      "dataplotClick": function(eventObj, dataObj) {
        if (getMode() === 'stackedBar') {
          var JSON = pieChart.getJSONData(),
            categoryLabel = dataObj.categoryLabel;
          JSON.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
          JSON.data = getProducts(categoryLabel);
          pieChart.setJSONData(JSON);
          pieChart.slicePlotItem(dataObj.datasetIndex);
        }
      }
    }
  }).render();

  function resetFN() {
    var json = pieChart.getJSONData();
    json.chart.subCaption = "Component-wise BreakUp";
    json.data = getComponents();
    pieChart.setJSONData(json);

    json = stackedChart.getJSONData();
    json.chart.subCaption = "Product-wise BreakUp";
    json.categories[0].category = getComponents(true, false);
    json.dataset = getData();
    stackedChart.setJSONData(json);
  }

  document.getElementById('reset').addEventListener('click', resetFN);
  document.getElementById('interaction').addEventListener('change', resetFN);

});
h4 {
  font-size: 20px;
  margin-bottom: 10px
}

.intro {
  margin: 0 auto;
  background-color: #fff280;
  padding: 15px
}

em {
  font-style: italic
}

#interactionWrapper {
  margin: 5px 10px;
}

button {
  border: 1px solid #0b77bc;
  background-color: #0d83ce;
  color: #ffffff;
  margin: 10px 0 0 15px;
  padding: 5px 10px;
  font-size: 14px;
  cursor: pointer
}

.centerAlign {
  text-align: center;
}
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<div class="intro">
  <h4>Expenditures incurred while publishing books</h4>
  <p><em>A company has 6 books to publish for this quater. The stacked chart shows component prices stacked as per different books. While the pie chart, shows the cumilative component price.</em></p>
  <p>
    <em>There are two interaction modes - namely "Interact in stacked chart" and "Interact in pie chart".On clicking in any plot on stacked chart, it shows the book-wise distribution of that component in the pie chart. Whereas on clicking the pie chart, for a component being clicked, it shows the book-wise distribution in the bar chart</em>
  </p>
</div>
<div id="interactionWrapper">
  <span>Interaction Mode:</span>
  <span>
            <select id="interaction">
              <option value="stackedBar">Interact in stacked bar</option>
              <option value="pie">Interact in the pie chart</option>
            </select>
        </span>
</div>
<div class="centerAlign">
  <span id="barContainer">FusionCharts XT will load here!</span>
  <span id="pieContainer">FusionCharts XT will load here!</span>
</div>
<button id="reset">Reset</button>

关于javascript - 在同一页面上创建钻取融合图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775848/

相关文章:

javascript - 分离出对象内的对象数组(Javascript)

php - 从 SQL 表中检索数据

php - 如何使用来自 MySQL 数据库的数据使用 fusioncharts 创建组合图(条形图和折线图)?

javascript - 当 <base> 标签包含在 HTML head 中时,FusionCharts 无法正确呈现

javascript - 如何在nodejs中获取项目的单独id

javascript - ng-repeat 不遍历 JSON 中的图像列表

javascript - 使用 getElementById 查找子元素

php - 防止站点导航重叠标题

php - symfony 错误 : Expected =, <, <=, <>, >, >=, !=, 得到 '.'

javascript - 使用 jquery 显示图例