如何使用2个数据值/数字列创建饼图或甜甜圈图

时间:2020-05-14 16:39:35

标签: javascript php html pie-chart donut-chart

我想创建饼图或甜甜圈图,标签为storage_typestorage_usedstorage_freestorage_type的标签是字符串,storage_used是数字,storage_free是数字。在饼图中仅输出storage_free,而不在storage_usedstorage_free之间进行组合。我希望饼图在storage_usedstorage_free之间结合起来。

<?php

        $tmp=array();

        require "configdashboard.php";
        /*
            select the 3 columns of interest, assinging aliases for laziness purposes
        */
        $sql="select `storage_type` as `type`,`storage_used` as `used`, `storage_free` as `free` 
            from `storage` 
            where `storage_type`='fujitsu';";


        if( $stmt = $connection->query( $sql ) ){
            while( $row = $stmt->fetch_assoc() ) {

                /* Add each row with named columns - which makes working with the JSON in Javascript easier IMO */
                $tmp[] = array(
                    'type'  =>  $row['type'],
                    'used'  =>  $row['used'],
                    'free'  =>  $row['free']
                );
            }
        }

        # create the JSON string
        $json=json_encode( $tmp );
?>
<html>
<head>
</head>
<body>
<div id="chart_div" style="width: 500px; height: 55%; display: block; margin: auto;" ></div>

			<script src='//www.gstatic.com/charts/loader.js'></script>
			<script>
    var my_2d=<?php echo $json;?>;
	console.log(Object.keys(my_2d));

    google.charts.load('current', {packages: ['corechart']});
    google.charts.setOnLoadCallback( drawChart );

    function drawChart(){
        if( Object.keys( my_2d ).length > 0 ){
            var json= my_2d ;

            var dataTbl = new google.visualization.DataTable();
                dataTbl.addColumn('string', 'type');
                dataTbl.addColumn('number', 'used');
                dataTbl.addColumn('number', 'free');
            /*
                you should be able to access the properties of
                each record using names now rather than indices
            */
            Object.keys( json ).map( k=>{
                var obj=json[ k ];
                var data=[ 
                    obj.type,
                    parseFloat( obj.used ),
                    parseFloat( obj.free )
                ];

                dataTbl.addRow( data );
            });

            var options = {};
            var chart = new google.visualization.PieChart( document.getElementById('chart_div') );
                chart.draw( dataTbl, options );
        }
    }
</script>
</body>
</html>

此数据库 enter image description here

此输出 enter image description here

0 个答案:

没有答案