如何使用Google Chart Tools绘制“年龄 - 性别”样式柱形图?

时间:2012-12-13 18:01:21

标签: javascript html google-visualization

enter image description here

我可以绘制并排样式的柱形图和堆叠图表(全部在x轴上方),但不是这个。如何使x轴以下的值仍为正值?

1 个答案:

答案 0 :(得分:1)

如果您使用Column chart,请将isStacked属性设置为true,并将一个性别的值(示例中为女性)乘以-1,这将为您提供所需的条形图。接下来,您需要更改vAxis格式以隐藏否定符号。 Google图表存在一些限制,会使100%的此请求难以实现。最大的一点是Google Charts仅支持部分ICU pattern set,这意味着您无法将百分比修饰符添加到正值和负值。为了解决这个问题,我将百分比值乘以100而不是1.0的分数,这在技术上是正确的。另外正如您所指出的那样,工具提示显示负值。为了解决这个问题,你需要给出一个正值的女性基准的格式化值(在这种情况下你可以包括%,因为它只是一个字符串,而不是图表值)。

Google Code Playground试试这个:

function drawVisualization() {
  /* Create and populate the data table. */
  var data = {
    "cols":[
      {"id":"Age","label":"Age","type":"string"},
      {"id":"Female","label":"Female","type":"number"},
      {"id":"Male","label":"Male","type":"number"}
    ],"rows":[
      {
        "c":[
          {"v":13,"f":"13-17"},
          {"v":-11,"f":"11%"},
          {"v":2,"f":"2%"}]
      },
      {
        "c":[
          {"v":18,"f":"18-24"},
          {"v":-8,"f":"8%"},
          {"v":5,"f":"5%"}]
      },
      {
        "c":[
          {"v":25,"f":"25-34"},
          {"v":-6,"f":"6%"},
          {"v":8,"f":"8%"}]
      },
      {
        "c":[
          {"v":35,"f":"35-44"},
          {"v":-6,"f":"6%"},
          {"v":10,"f":"10%"}]
      },
      {
        "c":[
          {"v":45,"f":"45-54"},
          {"v":-8,"f":"8%"},
          {"v":12,"f":"12%"}]
      },
      {
        "c":[
          {"v":55,"f":"55-64"},
          {"v":-3,"f":"3%"},
          {"v":7,"f":"7%"}]
      },
      {
        "c":[
          {"v":64,"f":"64+"},
          {"v":-1,"f":"1%"},
          {"v":2,"f":"2%"}]
      }
    ]
  };

  /* Create and draw the visualization. */
  new google.visualization.ColumnChart(document.getElementById('visualization'))
    .draw(new google.visualization.DataTable(data), {
      title:"Coffee Consumption by age",
      isStacked: true,
      vAxis: {
        format: "##;##"
      },
      width:600, height:400,
      hAxis: {
        title: "Age"
      }
    }
  );
}

这是它的样子:

Stacked Chart