代码之家  ›  专栏  ›  技术社区  ›  I am the Most Stupid Person

谷歌图表图例位置顶部不工作

  •  3
  • I am the Most Stupid Person  · 技术社区  · 6 年前

    你可以用这个 jsfiddle 用于测试

    完整代码:

    google.load('visualization', '1.1', {
        'packages': ['bar']
    });
    google.setOnLoadCallback(drawStuff);
    
    function drawStuff() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Nescafe Instant');
        data.addColumn('number', 'Folgers Instant');
        data.addColumn('number', 'Nescafe Beans');
        data.addColumn('number', 'Folgers Beans');
        data.addRows([
            ['2001', 500, 1200, 816, 200],
            ['2002', 163, 231, 539, 594],
            ['2003', 125, 819, 200, 578],
            ['2004', 197, 536, 613, 500]
        ]);
    
        // Set chart options
        var options = {
            isStacked: true,
            width: 800,
            height: 600,
            legend: {
                position: "top",
                alignment: "",
                textStyle: {
                        color: "#999"
                    }
                },
            chart: {
                title: 'Year-by-year coffee consumption',
                subtitle: 'This data is not real'
            },
    
            series: {
                2: {
                    targetAxisIndex: 1
                },
                3: {
                    targetAxisIndex: 1
                }
            }
        };
    
    };
    

    问题 :

    我想在图表上方显示图例。我使用了图例位置:顶部。但它不起作用。我可以将图例移动到左侧或右侧,更改图例位置值时不会出现问题。

    但我无法将图例上移或下移。为什么会这样?我的错误是什么?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Adinia Nirmal Dhara    6 年前

    首先,您需要使用正确的库,如 jsapi 已过期,不应再使用,
    根据 release notes

    通过 jsapi 加载程序不再持续更新。请使用新的gstatic loader.js 从现在开始

    这只会改变 load 声明:

    古老的 加载语句。。。

    google.load('visualization', '1.1', {
      packages: ['bar']
    });
    

    加载语句。。。

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

    接下来,如上所述 经典 图表,使用--> packages: ['corechart']
    而不是 'bar'

    谷歌提供了一个图表选项 经典 图表 相像的 布料 :

    theme: 'material'
    

    创建时 经典 图表中,使用以下命名空间:

    google.visualization.ColumnChart
    

    vs。 布料

    google.charts.Bar
    

    请参阅以下工作片段:

    google.charts.load('current', {
      packages: ['corechart']
    }).then(function () {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Topping');
      data.addColumn('number', 'Nescafe Instant');
      data.addColumn('number', 'Folgers Instant');
      data.addColumn('number', 'Nescafe Beans');
      data.addColumn('number', 'Folgers Beans');
      data.addRows([
        ['2001', 500, 1200, 816, 200],
        ['2002', 163, 231, 539, 594],
        ['2003', 125, 819, 200, 578],
        ['2004', 197, 536, 613, 500]
      ]);
    
      var options = {
        chartArea: {
          height: '100%',
          width: '100%',
          top: 64,
          left: 64,
          right: 32,
          bottom: 32
        },
        height: '100%',
        width: '100%',
        isStacked: true,
        legend: {
          position: 'top',
          textStyle: {
            color: '#999'
          }
        },
        title: 'Year-by-year coffee consumption'
      };
    
      var container = document.getElementById('chart_div');
      var chart = new google.visualization.ColumnChart(container);
    
      drawChart();
      window.addEventListener('resize', drawChart, false);
      function drawChart() {
        chart.draw(data, options);
      }
    });
    html, body {
      height: 100%;
      margin: 0px 0px 0px 0px;
      overflow: hidden;
      padding: 0px 0px 0px 0px;
    }
    
    .chart {
      height: 100%;
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div class="chart" id="chart_div"></div>

    注:唯一的优势 布料 有多个堆栈,
    在里面 经典 ,不能将多个堆栈分组。


    使现代化

    没有可以更改的选项来将图例定位到顶部或底部,这是不受支持的。

    唯一的解决方案是手动构建自定义图例; 以下是 实例 如何做到这一点:

    google.charts.load('current', {
      packages: ['bar']
    }).then(function () {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Topping');
      data.addColumn('number', 'Nescafe Instant');
      data.addColumn('number', 'Folgers Instant');
      data.addColumn('number', 'Nescafe Beans');
      data.addColumn('number', 'Folgers Beans');
      data.addRows([
        ['2001', 500, 1200, 816, 200],
        ['2002', 163, 231, 539, 594],
        ['2003', 125, 819, 200, 578],
        ['2004', 197, 536, 613, 500]
      ]);
    
      var options = {
        chart: {
          title: 'coffee consumption',
          subtitle: 'This data is not real'
        },
        height: '100%',
        isStacked: true,
        legend: {
          position: 'none'
        },
        series: {
          2: {
            targetAxisIndex: 1
          },
          3: {
            targetAxisIndex: 1
          }
        },
        width: '100%'
      };
    
      var container = document.getElementById('chart_div');
      var chart = new google.charts.Bar(container);
    
      drawChart();
      window.addEventListener('resize', drawChart, false);
      function drawChart() {
        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    
      // add legend marker
      function addLegendMarker(markerProps) {
        var legendMarker = document.getElementById('template-legend-marker').innerHTML;
        for (var handle in markerProps) {
          if (markerProps.hasOwnProperty(handle)) {
            legendMarker = legendMarker.replace('{{' + handle + '}}', markerProps[handle]);
          }
        }
        document.getElementById('legend_div').insertAdjacentHTML('beforeEnd', legendMarker);
      }
    
      // chart ready event
      google.visualization.events.addListener(chart, 'ready', function () {
        var legend = document.getElementById('legend_div');
    
        // get colors from chart
        var colorPallette = [];
        var colorsBottom = [];
        var colorsTop = [];
        var stacks = container.getElementsByTagName('*');
        Array.prototype.forEach.call(stacks, function(stack) {
          switch (stack.tagName) {
            case 'path':
              if ((stack.getAttribute('fill') !== null) && (stack.getAttribute('fill') !== '#ffffff')) {
                if (colorsTop.indexOf(stack.getAttribute('fill')) === -1) {
                  colorsTop.push(stack.getAttribute('fill'));
                }
              }
              break;
    
            case 'rect':
              if ((stack.getAttribute('fill') !== null) && (stack.getAttribute('fill') !== '#ffffff')) {
                if (colorsBottom.indexOf(stack.getAttribute('fill')) === -1) {
                  colorsBottom.push(stack.getAttribute('fill'));
                }
              }
              break;
          }
        });
        for (var i = 0; i < colorsBottom.length; i++) {
          colorPallette.push(colorsBottom[i]);
          colorPallette.push(colorsTop[i]);
        }
    
        // clear previous legend
        legend.innerHTML = '';
    
        // add legend marker for each Y axis column - skip X axis --> i = 1
        for (var i = 1; i < data.getNumberOfColumns(); i++) {
          var markerProps = {};
          markerProps.index = i;
          markerProps.color = colorPallette[i - 1];
          markerProps.label = data.getColumnLabel(i);
          addLegendMarker(markerProps);
        }
    
        // add "hover" event to each legend marker
        var currentSelection;
        var markers = legend.getElementsByTagName('DIV');
        Array.prototype.forEach.call(markers, function(marker) {
          marker.addEventListener('mouseover', function (e) {
            currentSelection = chart.getSelection();
            var marker = e.target || e.srcElement;
            if (marker.tagName.toUpperCase() !== 'DIV') {
              marker = marker.parentNode;
            }
            var columnIndex = parseInt(marker.getAttribute('data-columnIndex'));
            chart.setSelection([{column: columnIndex}]);
          }, false);
          marker.addEventListener('mouseout', function (e) {
            chart.setSelection([]);
          }, false);
        });
      });
    });
    html, body {
      height: 100%;
      margin: 0px 0px 0px 0px;
      overflow: hidden;
      padding: 0px 0px 0px 0px;
    }
    
    .chart {
      height: 100%;
    }
    
    #legend_div {
      color: #999;
      font-family: Roboto;
      position: absolute;
      right: 0px;
      text-align: right;
      top: 0px;
      width: 60%;
      z-index: 1000;
    }
    
    .legend-marker {
      display: inline-block;
      padding: 6px 6px 6px 6px;
    }
    
    .legend-marker-color {
      border-radius: 25%;
      display: inline-block;
      height: 12px;
      width: 12px;
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="legend_div"></div>
    <div class="chart" id="chart_div"></div>
    
    <!-- template for building marker -->
    <script id="template-legend-marker" type="text/html">
      <div class="legend-marker" data-columnIndex="{{index}}">
        <div class="legend-marker-color" style="background-color: {{color}}"></div>
        <span>{{label}}</span>
      </div>
    </script>