Java脚本谷歌饼图:如果没有要显示的数据,则显示一个空饼图

时间:2017-03-09 12:39:55

标签: javascript jquery charts google-visualization

我目前在google饼图上遇到了一些问题。我有一个饼图,它最终正在工作,并向我显示饼图中的数据。

我现在的问题是,当饼图中没有数据显示时,什么都不会出现。如果没有要显示的数据,我想显示一个空的饼图。

作为替代方案,我也想总是显示一个空的饼图,然后让饼图动态加载饼图中的数据,这样我就可以看到它。

希望你们能帮助我!我真的很感激。

我目前有以下javascript: (更新版本)

    <div style="border: 0px solid rgb(201, 0, 1); overflow: hidden; margin: 15px auto; max-width: 100%;">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {packages: ['corechart']});
  google.charts.setOnLoadCallback(drawChart);
</script>
<script type="text/javascript">

var highRiskCategory1 = 0;
var mediumHighRiskCategory1 = 0;
var mediumRiskCategory1 = 0;
var mediumLowRiskCategory1 = 0;
var lowRiskCategory1 = 0;

var xmlURL = "";
var xml;

var firstDraw = true;

// load google first
google.charts.load('current', {
  callback: function () {
    // draw "no data" chart
    drawPiechartblank();
  },
  packages: ['corechart']
});

function loadData() {
  $j.ajax({
    url: xmlURL,
    dataType: 'xml',
    beforeSend: function() {
      $j('#loader').show();
    },
    success: function(data) {
      xml = data;
      $j('#loader').hide();
      createPiechartthree();
    },
    error: function(jqXHR, text) {
      console.log(text);
      drawPiechartblank();
      return;
    }
  });
}

function createPiechartthree(){
  var columns = {};
  var xmlColumns = $j('head', xml);
  xmlColumns.find('headColumn').each(function() {
    var columnName = $j(this).find('columnValue').text();
    var columnID = $j(this).attr('columnid');
    columns[columnName] = (columnID);
  });

  var xmlData = $j('data', xml);

  xmlData.find('item').each(function() {
    $j(this).find('column').each(function() {
      var colID = $j(this).attr("columnid");
      var value = $j(this).find('displayData').text();

      if(colID == columns["Risk category"]){
        if(value === "5. High Risk"){
          highRiskCategory1++;
        }
        else if(value === "4. Medium High Risk"){
          mediumHighRiskCategory1++;
        }
        else if(value === "3. Medium Risk"){
          mediumRiskCategory1++;
        }
        else if(value === "2. Medium Low Risk"){
          mediumLowRiskCategory1++;
        }
        else if(value === "1. Low Risk"){
          lowRiskCategory1++;
        }
      }
    });
  });

  // check for data
  if ((highRiskCategory1 + mediumHighRiskCategory1 + mediumRiskCategory1 + mediumLowRiskCategory1 + lowRiskCategory1) === 0) {
    drawPiechartblank();
  } else {
    drawPiechartthree(highRiskCategory1, mediumHighRiskCategory1, mediumRiskCategory1, mediumLowRiskCategory1, lowRiskCategory1);
  }
}

function drawPiechartthree(highRiskCategory1, mediumHighRiskCategory1, mediumRiskCategory1, mediumLowRiskCategory1, lowRiskCategory1) {
  var data = google.visualization.arrayToDataTable([
    ['Is the counterparty a PEP?', 'Amount'],
    ['Very low', 0],
    ['High Risk', highRiskCategory1],
    ['Medium High Risk', mediumHighRiskCategory1],
    ['Medium Risk', mediumRiskCategory1],
    ['Medium Low Risk', mediumLowRiskCategory1],
    ['Low Risk', lowRiskCategory1],
    ['Very high',  0]
  ]);

  var options = {
    chartArea: {
      // allow room for selection highlight
      bottom: 12,
      left: 12,
      right: 12,
      top: 12,

      height: '100%',
      width: '100%'
    },
    pieHole: 0.5,
    colors: ['#25b578', '#f05023', '#FF944A', '#F6BD53', '#FFE158', '#6FC968', '#8C8886'],
    slices: {
      2: {offset: 0.02},
      3: {offset: 0.02},
      4: {offset: 0.02},
      5: {offset: 0.02},
    },
  };

  var chart = new google.visualization.PieChart(
  document.getElementById('Piechartthree_div'));
  chart.draw(data, options);

  var selectHandler = function(e) {
    var selectedItem = chart.getSelection()[0];
    if (selectedItem) {
      var topping = data.getValue(selectedItem.row, 0);
      console.log(topping);
      if(topping === 'High Risk'){
        window.location.href = '';
      }
      else if(topping === 'Medium High Risk'){
        window.location.href = '';
      }
      else if(topping === 'Medium Risk'){
        window.location.href = '';
      }
      else if(topping === 'Medium Low Risk'){
        window.location.href = '';
      }
      else if(topping === 'Low Risk'){
        window.location.href = '';
      }
    }
  }
  google.visualization.events.addListener(chart, 'select', selectHandler);
}

function drawPiechartblank() {
  var data = google.visualization.arrayToDataTable([
    ['Is the counterparty a PEP?', 'Amount'],
    // blank first column removes legend,
    // use object notation for formatted value (f:)
    ['', {v: 1, f: 'No Data'}]
  ]);

  var options = {
    chartArea: {
      bottom: 12,
      left: 12,
      right: 12,
      top: 12,
      height: '100%',
      width: '100%'
    },
    pieHole: 0.5,
    colors: ['transparent'],
    pieSliceBorderColor: '#9e9e9e',
    // show formatted value from the data
    pieSliceText: 'value',
    // default text style is white
    // won't show in center unless change color
    pieSliceTextStyle: {
      color: '#9e9e9e'
    },
    tooltip: {
      trigger: 'none'
    }
  };

  var chart = new google.visualization.PieChart(
    document.getElementById('Piechartthree_div')
  );
  google.visualization.events.addListener(chart, 'ready', function () {
    // load data on first draw
    if (firstDraw) {
      firstDraw = false;
      loadData();
    }
  });
  chart.draw(data, options);
}
</script>
<div id="Piechartthree_div" style="width: 100%; height: ; position:relative;"><img alt="" id="" src="./attachment_dw.action?attachmentId=2233" style="width: 80px; height: 80px; display: inline-block;  position:absolute; right:50%; top: 50%;" /></div>
</div>

1 个答案:

答案 0 :(得分:0)

为了绘制饼图,谷歌需要至少一行,其值大于零

所以只需硬编码所需的数据......

  var data = google.visualization.arrayToDataTable([
    ['Is the counterparty a PEP?', 'Amount'],
    ['', {v: 1, f: 'No Data'}]
  ]);

对行标签使用空白字符串''将阻止图例显示
使用格式化的值f:在饼图中心显示文本 这需要以下选项......

    // show formatted value from the data
    pieSliceText: 'value',

    // default text style is white
    // won't show in center unless change color
    pieSliceTextStyle: {
      color: '#9e9e9e'
    },

使图表看起来为空,使用透明作为颜色并添加边框...

    colors: ['transparent'],
    pieSliceBorderColor: '#9e9e9e',

请参阅以下工作代码段...

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

function drawPiechartblank() {
  var data = google.visualization.arrayToDataTable([
    ['Is the counterparty a PEP?', 'Amount'],
    // blank first column removes legend,
    // use object notation for formatted value (f:)
    ['', {v: 1, f: 'No Data'}]
  ]);

  var options = {
    chartArea: {
      bottom: 12,
      left: 12,
      right: 12,
      top: 12,
      height: '100%',
      width: '100%'
    },
    pieHole: 0.5,
    colors: ['transparent'],
    pieSliceBorderColor: '#9e9e9e',
    // show formatted value from the data
    pieSliceText: 'value',
    // default text style is white
    // won't show in center unless change color
    pieSliceTextStyle: {
      color: '#9e9e9e'
    },
    tooltip: {
      trigger: 'none'
    }
  };

  var chart = new google.visualization.PieChart(
    document.getElementById('Piechartthree_div')
  );
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="Piechartthree_div"></div>

图表开头,先加载谷歌,绘制空白图表

// load google first
google.charts.load('current', {
  callback: function () {
    // draw "no data" chart
    drawPiechartblank();
  },
  packages: ['corechart']
});

然后在发送第一个数据请求之前等待'ready'事件...

  google.visualization.events.addListener(chart, 'ready', function () {
    if (firstDraw) {
      firstDraw = false;
      loadData();
    }
  });

请参阅以下代码段,注释中有注释......

<div style="border: 0px solid rgb(201, 0, 1); overflow: hidden; margin: 15px auto; max-width: 100%;">
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>

var highRiskCategory1 = 0;
var mediumHighRiskCategory1 = 0;
var mediumRiskCategory1 = 0;
var mediumLowRiskCategory1 = 0;
var lowRiskCategory1 = 0;

var xmlURL = "XMLLINK";
var xml;

var firstDraw = true;

// load google first
google.charts.load('current', {
  callback: function () {
    // draw "no data" chart
    drawPiechartblank();
  },
  packages: ['corechart']
});

function loadData() {
  $j.ajax({
    url: xmlURL,
    dataType: 'xml',
    beforeSend: function() {
      $j('#loader').show();
    },
    success: function(data) {
      xml = data;
      $j('#loader').hide();
      createPiechartthree();
    },
    error: function(jqXHR, text) {
      drawPiechartblank();
      return;
    }
  });
}

function createPiechartthree(){
  var columns = {};
  var xmlColumns = $j('head', xml);
  xmlColumns.find('headColumn').each(function() {
    var columnName = $j(this).find('columnValue').text();
    var columnID = $j(this).attr('columnid');
    columns[columnName] = (columnID);
  });

  var xmlData = $j('data', xml);

  xmlData.find('item').each(function() {
    $j(this).find('column').each(function() {
      var colID = $j(this).attr("columnid");
      var value = $j(this).find('displayData').text();

      if(colID == columns["Risk category"]){
        if(value === "5. High Risk"){
          highRiskCategory1++;
        }
        else if(value === "4. Medium High Risk"){
          mediumHighRiskCategory1++;
        }
        else if(value === "3. Medium Risk"){
          mediumRiskCategory1++;
        }
        else if(value === "2. Medium Low Risk"){
          mediumLowRiskCategory1++;
        }
        else if(value === "1. Low Risk"){
          lowRiskCategory1++;
        }
      }
    });
  });

  // check for data
  if ((highRiskCategory1 + mediumHighRiskCategory1 + mediumRiskCategory1 + mediumLowRiskCategory1 + lowRiskCategory1) === 0) {
    drawPiechartblank();
  } else {
    drawPiechartthree(highRiskCategory1, mediumHighRiskCategory1, mediumRiskCategory1, mediumLowRiskCategory1, lowRiskCategory1);
  }
}

function drawPiechartthree(highRiskCategory1, mediumHighRiskCategory1, mediumRiskCategory1, mediumLowRiskCategory1, lowRiskCategory1) {
  var data = google.visualization.arrayToDataTable([
    ['Is the counterparty a PEP?', 'Amount'],
    ['Very low', 0],
    ['High Risk', highRiskCategory1],
    ['Medium High Risk', mediumHighRiskCategory1],
    ['Medium Risk', mediumRiskCategory1],
    ['Medium Low Risk', mediumLowRiskCategory1],
    ['Low Risk', lowRiskCategory1],
    ['Very high',  0]
  ]);

  var options = {
    chartArea: {
      // allow room for selection highlight
      bottom: 12,
      left: 12,
      right: 12,
      top: 12,

      height: '100%',
      width: '100%'
    },
    pieHole: 0.5,
    colors: ['#25b578', '#f05023', '#FF944A', '#F6BD53', '#FFE158', '#6FC968', '#8C8886'],
    slices: {
      2: {offset: 0.02},
      3: {offset: 0.02},
      4: {offset: 0.02},
      5: {offset: 0.02},
    },
  };

  var chart = new google.visualization.PieChart(
  document.getElementById('Piechartthree_div'));
  chart.draw(data, options);

  var selectHandler = function(e) {
    var selectedItem = chart.getSelection()[0];
    if (selectedItem) {
      var topping = data.getValue(selectedItem.row, 0);
      console.log(topping);
      if(topping === 'High Risk'){
        window.location.href = '';
      }
      else if(topping === 'Medium High Risk'){
        window.location.href = '';
      }
      else if(topping === 'Medium Risk'){
        window.location.href = '';
      }
      else if(topping === 'Medium Low Risk'){
        window.location.href = '';
      }
      else if(topping === 'Low Risk'){
        window.location.href = '';
      }
    }
  }
  google.visualization.events.addListener(chart, 'select', selectHandler);
}

function drawPiechartblank() {
  var data = google.visualization.arrayToDataTable([
    ['Is the counterparty a PEP?', 'Amount'],
    // blank first column removes legend,
    // use object notation for formatted value (f:)
    ['', {v: 1, f: 'No Data'}]
  ]);

  var options = {
    chartArea: {
      bottom: 12,
      left: 12,
      right: 12,
      top: 12,
      height: '100%',
      width: '100%'
    },
    pieHole: 0.5,
    colors: ['transparent'],
    pieSliceBorderColor: '#9e9e9e',
    // show formatted value from the data
    pieSliceText: 'value',
    // default text style is white
    // won't show in center unless change color
    pieSliceTextStyle: {
      color: '#9e9e9e'
    },
    tooltip: {
      trigger: 'none'
    }
  };

  var chart = new google.visualization.PieChart(
    document.getElementById('Piechartthree_div')
  );
  google.visualization.events.addListener(chart, 'ready', function () {
    // load data on first draw
    if (firstDraw) {
      firstDraw = false;
      loadData();
    }
  });
  chart.draw(data, options);
}
</script>
<div id="Piechartthree_div" style="width: 100%; height: ; position:relative;"><img alt="" id="" src="./attachment_dw.action?attachmentId=2233" style="width: 80px; height: 80px; display: inline-block;  position:absolute; right:50%; top: 50%;" /></div>
</div>

注意:建议使用较新的库loader.js与较旧的jsapi

根据release notes ...

  

通过jsapi加载程序保留的Google Charts版本不再一致更新。从现在开始请使用新的gstatic装载机。

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

这只会更改load声明...