如何使用Google图表在条形图的顶部插入点? [英] How to insert points on top of bar charts using Google Charts?

查看:68
本文介绍了如何使用Google图表在条形图的顶部插入点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出插图



< img src = https://i.stack.imgur.com/zYiRM.png alt =在此处输入图片描述>



我曾经能够使用以下代码创建图表(不包含点):

 < html> 
< head>
< script type = text / javascript src = https://www.gstatic.com/charts/loader.js>< / script>
< script type = text / javascript>
google.charts.load(‘current’,{’packages’:[’bar’]});
google.charts.setOnLoadCallback(drawStuff);

var图表;

函数drawStuff(){
var data = new google.visualization.arrayToDataTable([
['Y','Series 1','Series 2'],
[元素A,44,11],
[元素B,31,11],
[元素C,12,11],
]);

var选项= {
条形:水平,//实心条形图必需。
轴:{
x:{
0:{侧面:底部,标签: X}} //顶部x轴。
}
}
};

var div = document.getElementById(’top_x_div');
var link = document.getElementById(’url’);
chart = new google.charts.Bar(div);
chart.draw(数据,选项);
//console.log(chart.getImageURI());
};
< / script>
< / head>
< body>
< div id = top_x_div style = width:900px; height:500px;>< / div>
< / body>
< / html>

如何使用Google图表在条形图顶部插入点?

解决方案

我想到了几种方法来完成...


  1. 使用组合图

  2. 在图表的就绪 事件上手动添加点

但是,使用材料图表都无法实现任何选择。

  google.charts.Bar 

首先,材料图表不支持组合图表。

材料图表没有手动添加点所必需的方法


更不用说,还有 material 图表中的几个选项不支持。

参见-> 物料图特征奇偶校验#2143的跟踪问题


,因此我们必须使用经典图表...

  google.visualization.BarChart 

我们可以使用一个选项为经典图表提供相似 >外观为 material 图表...

 主题: material 




现在的解决方案...


当尝试使用组合图时,

的点与y轴对齐,在两个条之间。

没有选择,允许这些点在上对齐
,因此我们必须在图表的就绪 事件上手动添加点...


几乎没有图表方法 w e需要...


getChartLayoutInterface()-返回一个对象,该对象包含有关屏幕上放置位置的信息


getBoundingBox(id)-返回一个包含图表左侧,顶部,宽度和高度的对象


getXLocation(position,optional_axis_index)-返回相对于图表容器的屏幕x坐标。

p>

一旦图表的'ready'事件触发,我们可以使用-> getChartLayoutInterface()


上面提到的其他两个方法是布局接口的方法。


我们使用 getBoundingBox(id)来获取要放置点的条的坐标。

这将使我们得到Y坐标和点的高度。

条形图的ID由数据行和系列列确定。

  bar#C#R // // C是系列列索引,R是行索引

提供X坐标,

getXLocation 将提供图表上的位置(将点放置在x轴上)在我们预定的位置。

  // x要添加
的点的坐标var points = [
[36,8],
[28,8],
[10,8],
];

//循环数据行和列
for(var r = 0; r< data.getNumberOfRows(); r ++){
for(var c = 1; c < data.getNumberOfColumns(); c ++){
//计算点的位置
var barBounds = chartLayout.getBoundingBox('bar#'+(c-1)+'#'+ r) ;
var xCoord = chartLayout.getXLocation(points [r] [c-1]);
var height = barBounds.height / 4;
var top = barBounds.top +(高度* 2);

//创建点并将其添加到图表
var point = document.createElementNS(svgNS,'circle');
point.setAttribute(’cx’,xCoord);
point.setAttribute('cy',top);
point.setAttribute(’r’,height);
point.setAttribute('stroke','#ffffff');
point.setAttribute('stroke-width',height);
point.setAttribute('fill','transparent');
svg.appendChild(point);
}
}

请参阅以下工作片段...


< pre class = snippet-code-js lang-js prettyprint-override> var chart;

google.charts.load('current',{
包:['corechart']
})。then(function drawStuff(){
var data = new google.visualization.arrayToDataTable([
['Y','Series 1','Series 2'],
['Element A',44,11],
['元素B',31、11],
['元素C',12、11],
]);

// x要添加$ b $的点的坐标b变量点= [
[36,8],
[28,8],
[10,8],
];

var选项= {
图表区域:{
左:128,
顶部:24,
右:128,
底部:72,
高度:'100 %',
宽度:'100%'
},
hAxis:{
标题:'X'
},
高度:'100% ',
主题:'material',
vAxis:{
标题:data.getColumnLabel(0)
},
宽度:'100%'
};

var div = document.getElementById('top_x_div');
// var link = document.getElementById('url');

图表= ne w google.visualization.BarChart(div);

google.visualization.events.addListener(图表,'就绪',函数(){
//获取图表布局接口和svg
var chartLayout = chart.getChartLayoutInterface() ;
var svg = div.getElementsByTagName('svg')[0];
var svgNS = svg.namespaceURI;

//循环数据行和列
for(var r = 0; r< data.getNumberOfRows(); r ++){
for(var c = 1; c< data.getNumberOfColumns(); c ++){
//计算位置
的点var barBounds = chartLayout.getBoundingBox('bar#'+(c-1)+'#'+ r);
var xCoord = chartLayout.getXLocation(points [r] [c- 1]);
var height = barBounds.height / 4;
var top = barBounds.top +(height * 2);

//创建并添加点到图表
var point = document.createElementNS(svgNS,'circle');
point.setAttribute('cx',xCoord);
point.setAttribute('cy',top);
点t.setAttribute(’r’,height);
point.setAttribute('stroke','#ffffff');
point.setAttribute('stroke-width',height);
point.setAttribute('fill','transparent');
svg.appendChild(point);
}
}
});

chart.draw(数据,选项);
window.addEventListener('resize',function(){
chart.draw(data,options);
});
});

  #top_x_div {
高度:400像素;
}

 < script src = https ://www.gstatic.com/charts/loader.js< / script> 
< div id = top_x_div>< / div>


Given the illustration

I was able to create the chart (without the points) using the following code:

<html>
  <head>
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawStuff);

      var chart;

      function drawStuff() {
        var data = new google.visualization.arrayToDataTable([
          ['Y', 'Series 1','Series 2'],
          ["Element A", 44,11],
          ["Element B", 31,11],
          ["Element C", 12,11],
        ]);

        var options = {
          bars: 'horizontal', // Required for Material Bar Charts.
          axes: {
            x: {
              0: { side: 'bottom', label: 'X'} // Top x-axis.
            }
          }
        };

        var div = document.getElementById('top_x_div');
        var link = document.getElementById('url');
        chart = new google.charts.Bar(div);
        chart.draw(data, options);
        //console.log(chart.getImageURI());
      };
    </script>
  </head>
  <body>
    <div id="top_x_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

How to insert points on top of bar charts using Google Charts?

解决方案

there were a couple ways I thought of, to accomplish...

  1. Use a Combo chart
  2. Add the points manually, on the chart's 'ready' event

however, neither option can be achieved using a material chart.

google.charts.Bar

first, material charts do not support Combo charts.
and, material charts do not have the methods necessary to add the points manually.

not to mention, there are also several options that material charts do not support.
see --> Tracking Issue for Material Chart Feature Parity #2143

so we must use a classic chart...

google.visualization.BarChart

there is an option we can use to give the classic chart a similar look and feel as material charts...

theme: 'material'


now the solution...

when attempting to use a Combo chart,
the points align to the y-axis, in between the two bars.
there is not an option that will allow the points to align on the bars.
so we must add the points manually, on the chart's 'ready' event...

there are few chart methods we need...

getChartLayoutInterface() - Returns an object containing information about the onscreen placement of the chart and its elements.

getBoundingBox(id) - Returns an object containing the left, top, width, and height of chart element id.

getXLocation(position, optional_axis_index) - Returns the screen x-coordinate of position relative to the chart's container.

once the chart's 'ready' event fires, we can get the layout interface using --> getChartLayoutInterface()

the other two methods mentioned above are methods of the layout interface.

we use getBoundingBox(id) to get the coordinates of the bar, on which the point will be placed.
this will give us the Y coordinate, and the height of the point.
the id of the bar is determined by the data row and series column.

bar#C#R  // where C is the series column index, and R is the row index

we are providing the X coordinate,
getXLocation will provide the location on the chart, needed to place the point on the x-axis, at our predetermined location.

// x coordinates of points to add
var points = [
  [36, 8],
  [28, 8],
  [10, 8],
];

// loop data rows and columns
for (var r = 0; r < data.getNumberOfRows(); r++) {
  for (var c = 1; c < data.getNumberOfColumns(); c++) {
    // calculate position of the point
    var barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
    var xCoord = chartLayout.getXLocation(points[r][c - 1]);
    var height = barBounds.height / 4;
    var top = barBounds.top + (height * 2);

    // create and add the point to the chart
    var point = document.createElementNS(svgNS, 'circle');
    point.setAttribute('cx', xCoord);
    point.setAttribute('cy', top);
    point.setAttribute('r', height);
    point.setAttribute('stroke', '#ffffff');
    point.setAttribute('stroke-width', height);
    point.setAttribute('fill', 'transparent');
    svg.appendChild(point);
  }
}

see following working snippet...

var chart;

google.charts.load('current', {
  packages: ['corechart']
}).then(function drawStuff() {
  var data = new google.visualization.arrayToDataTable([
    ['Y', 'Series 1', 'Series 2'],
    ['Element A', 44, 11],
    ['Element B', 31, 11],
    ['Element C', 12, 11],
  ]);

  // x coordinates of points to add
  var points = [
    [36, 8],
    [28, 8],
    [10, 8],
  ];

  var options = {
    chartArea: {
      left: 128,
      top: 24,
      right: 128,
      bottom: 72,
      height: '100%',
      width: '100%'
    },
    hAxis: {
      title: 'X'
    },
    height: '100%',
    theme: 'material',
    vAxis: {
      title: data.getColumnLabel(0)
    },
    width: '100%'
  };

  var div = document.getElementById('top_x_div');
  //var link = document.getElementById('url');

  chart = new google.visualization.BarChart(div);

  google.visualization.events.addListener(chart, 'ready', function () {
    // get chart layour interface and svg
    var chartLayout = chart.getChartLayoutInterface();
    var svg = div.getElementsByTagName('svg')[0];
    var svgNS = svg.namespaceURI;

    // loop data rows and columns
    for (var r = 0; r < data.getNumberOfRows(); r++) {
      for (var c = 1; c < data.getNumberOfColumns(); c++) {
        // calculate position of the point
        var barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
        var xCoord = chartLayout.getXLocation(points[r][c - 1]);
        var height = barBounds.height / 4;
        var top = barBounds.top + (height * 2);

        // create and add the point to the chart
        var point = document.createElementNS(svgNS, 'circle');
        point.setAttribute('cx', xCoord);
        point.setAttribute('cy', top);
        point.setAttribute('r', height);
        point.setAttribute('stroke', '#ffffff');
        point.setAttribute('stroke-width', height);
        point.setAttribute('fill', 'transparent');
        svg.appendChild(point);
      }
    }
  });

  chart.draw(data, options);
  window.addEventListener('resize', function () {
    chart.draw(data, options);
  });
});

#top_x_div {
  height: 400px;
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="top_x_div"></div>

这篇关于如何使用Google图表在条形图的顶部插入点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆