2016-08-04 5 views
1

내가 물었던 것을 검색하면 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> 

답변

1
  • n FusionCharts를 번호를 사용하여 한 페이지에 렌더링 될 수있다.
  • 차트 참조를 저장하십시오 (예 : 연관 배열에서.
  • dataplotClick 이벤트를 사용하여 데이터를 클릭하여 생성되는 이벤트를 캡처하십시오.
  • 콜백 내부에서 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>

관련 문제