Включить / отключить элементы легенды при первой загрузке страницы в диаграмме C3 Js.Также, управление включением / отключением элементов легенды на основе значения флажка - PullRequest
0 голосов
/ 15 октября 2018

Я не могу отключить элементы легенды диаграммы c3 js при загрузке страницы.(в конфиге графика).Кроме того, у меня есть требование включать / отключать элементы легенды диаграммы на основе значения флажка.Пробовал найти в документах c3 js, но не смог найти.

                 $scope.cpuChartArea = {
            data: {
                x: 'x',
                columns: [
                    xLabels,
                    data1,
                    data2,
                    data3
                ],
                xFormat: '%m-%d-%Y %H:%M:%S',
                types: {
                    'data 1': 'area-spline',
                    'data 2': 'area-spline',
                    'data 3': 'area-spline',

                }
            },
            point: {
                show: false
            },
            axis: {
                y: {
                    tick: {
                        format: function (d) { return d + "%"; }
                    }
                },
                x: {
                    type: 'timeseries',
                    tick: {
                        //format: function (x) { return x.getFullYear(); }
                        format: '%H:%M' // format string is also available for timeseries data
                    }
                }
            },
            tooltip:{
                format:{
                    title:function (x) { return x.getDate() + "/" + x.getMonth() + "/" + x.getFullYear() + " " + x.getHours()+ ":" + x.getMinutes() },
                }
            }
        }

1 Ответ

0 голосов
/ 24 октября 2018

Я понимаю, что вы используете Angular, но в простом JS легенда для каждой серии может быть показана / скрыта как

chart.legend.show('series id');

, где вы заменяете «идентификатор серии» на один из ваших рядов данных yнапример, «data 1» в вашем случае.

Рабочий фрагмент ниже - это чистая версия JS, основанная на вашей конфигурации диаграммы.Флажки показывают, что легенда для каждой серии может быть легко скрыта и раскрыта.Если вам нужна помощь в понимании события click, дайте мне знать - все, что он делает, это фиксирует изменение в флажке и в зависимости от состояния показывает или скрывает легенду для серии с соответствующим идентификатором.

Надеюсь, вы сможетеприспособьте это обучение к вашему угловому случаю.

var chart = c3.generate(
{
    bindto: '#chart',
    size: {
      width: 600,
      height: 140
    },
  data: {
    x: 'xLabels',
    columns: [
      ['xLabels', '2015-09-17 18:20:34','2015-09-17 18:25:42','2015-09-17 18:30:48'],
     ['data 1', 5,10,12],
     ['data 2', 4,13,17],
    ],
    xFormat: '%Y-%m-%d %H:%M:%S', // ### IMPORTANT - this is how d3 understands the date formatted in the xLabels array. If you do not alter this to match your data format then the x axis will not plot! 
    types: {
      'data 1': 'area-spline',
      'data 2': 'area-spline'
    }
  },
  point: {
    show: false
    
  },
  legend: {
      position: 'inset',
  inset: {
      anchor: 'top-left',
      x: 20,
      y: 10,
      step: 2
    }
  },
  axis: {
    y: {
      tick: {
        format: function (d) { return d + "%"; }
      }
    },
    x: {
      type: 'timeseries',
      tick: {
        //format: function (x) { return x.getFullYear(); }
        //format: '%H:%M' // format string is also available for timeseries data
        format: '%Y-%m-%d %H:%M:%S' // how the date is displayed
      }
    }
  }, 
  tooltip:{
    format:{
      title:function (x) { return x.getDate() + "/" + x.getMonth() + "/" + x.getFullYear() + " " + x.getHours()+ ":" + x.getMinutes() },
    }
  }  
})

// this is all about toggling the legends.
$('.checkBox').on('change', function(e){

  if ( $(this).prop('checked')){
    chart.legend.show($(this).attr('id'))
  }
  else {
    chart.legend.hide($(this).attr('id'))
  }

})
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.7/c3.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.7/c3.min.js"></script>

<p>Show legends: <label for='data 1'> data 1 </label><input type='checkbox' class='checkBox' id='data 1' checked='true'/><label for='data 2'>data 2 </label><input type='checkbox' class='checkBox' id='data 2' checked='true'/>  </p>

<div class='chart-wrapper'>
<div class='chat' id="chart"></div>
</div>
...