【问题标题】:Stacked bar chart using google charts api使用谷歌图表 api 堆积条形图
【发布时间】:2023-04-01 23:00:01
【问题描述】:

我已经成功地制作了一个基于 mysql 值的谷歌条形图。现在我想做它堆叠图表

我已经看到了很多例子,并且发现这种效果是使用 chco、cht、chd 等图表参数以及图表 api url 生成的,即这样的:

http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World

我试图使用mysql制作条形图的基本方法制作图表,即从mysql中获取数据并将其编码为json并将其发送到图表脚本,例如:

图表代码:

  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
        var json = $.ajax({
            url: 'get_json_rank.php', // make this url point to the data file
            dataType: 'json',
            async: false
        }).responseText;

        // Create our data table out of JSON data loaded from server.
        var data = new google.visualization.DataTable(json);
        var options = {
            legend: { position: 'none' },
            is3D: 'true',
            width: 500,
            height: 320,
            colors:['#4D515D'],
            hAxis: {
                textPosition:'none',
                title: "Restaurants"},
            vAxis: {
                title: "Business Growth",
                }
        };
        // Instantiate and draw our chart, passing in some options.
        //do not forget to check ur div ID
        var chart = new google.visualization.BarChart(document.getElementById('rank_chart'));
        chart.draw(data, options);

        setInterval(drawChart, 500 );
    }
</script>

我想在图表中添加以下参数,其中必须包含 php 变量,因为它们代表栏中的男女比例:

        cht='bhs',
        chco='4D89F9','C6D9FD'
        chd='t:'+ <?php echo $a; ?> +'|'+ <?php echo $b;?>,
        chds='0,160'

现在有人可以告诉我如何将这个简单的条形图变成堆叠的。任何帮助都将不胜感激。

【问题讨论】:

    标签: javascript php google-visualization


    【解决方案1】:

    您可以使用选项获得堆积条形图:

    isStacked: true
    

    is3D: 'true' 是用于饼图的选项。

    选项chco, cht, chd... 用于已弃用的图像图表。见谷歌Image charts

    【讨论】: