Ярлыки вертикальной оси установлены посередине в Google Visualization Chart - PullRequest
1 голос
/ 14 февраля 2020

Я использую пузырьковую диаграмму визуализации Google. Мне нужно выровнять метки по вертикальной оси к середине. Смотрите изображение ниже, пожалуйста. Что-то вроде этого. Эти названия месяцев должны быть между основными линиями сетки.

enter image description here

Вот параметры, которые я добавил для этой пузырьковой диаграммы, но она отображается только рядом с линией оси.

var options = {
        sizeAxis: {
            maxSize: 7,
            minSize: 1
        },
        animation: {
            duration: 1500,
            easing: 'in',
            startup: true
        },

        fontSize: 10,
        legend: 'none',
        height: 230,
        chartArea: { left: "20%", right: 0, top: 0, width: "70%", height: "200px" },


        bubble: { stroke: '#ffca18', opacity: 1 },
        colors: ['#ffca18', '#ffca18'],
        tooltip: {
            trigger: 'none'
        },
        hAxis: {
            ticks: [
                { v: 2015, f: '2015' },
                { v: 2016, f: '2016' },
                { v: 2017, f: '2017' },
                { v: 2018, f: '2018' },
                { v: 2019, f: '2019' },
                { v: 2019, f: '2020' }
            ],

            gridlines: { color: '#dedede' },
            minorGridlines: { color: '#f7f7f7', count: 3 },
            textStyle: { color: '#5f5f5f' }
        },
        vAxis: {
            ticks: [                   
                { v: 1, f: 'May' },
                { v: 2, f: 'April' },
                { v: 3, f: 'March' },
                { v: 4, f: 'February' },
                { v: 5, f: 'January' }
            ],
            gridlines: { color: '#dedede' },
            textStyle: { color: '#5f5f5f' },
            viewWindowMode: 'explicit',
            viewWindow: {
                min: 1,
                max: 7
            }
        }
    };

1 Ответ

0 голосов
/ 18 февраля 2020

мы можем переместить метки вручную, для события 'ready' на графике,
или, в данном случае, для события 'animationfinish' или для обоих.

у диаграммы есть метод для getChartLayoutInterface()
, который возвращает объект, который мы можем использовать для размещения различных элементов диаграммы.

мы можем получить расположение линий сетки,
и переместить метки между ними.

function moveYAxisLabels() {
  var chartLayout = chart.getChartLayoutInterface();
  var labels = chart.getContainer().getElementsByTagName('text');
  var labelIndex = -1;
  Array.prototype.forEach.call(labels, function(label) {
    if (label.getAttribute('text-anchor') === 'end') {
      labelIndex++;
      labelHeight = chartLayout.getBoundingBox('vAxis#0#label#' + labelIndex).height;
      labelBottom = chartLayout.getBoundingBox('vAxis#0#gridline#' + labelIndex).top;
      labelTop = chartLayout.getBoundingBox('vAxis#0#gridline#' + (labelIndex + 1)).top;
      label.setAttribute('y', labelBottom - ((labelBottom - labelTop) / 2) + Math.floor(labelHeight / 2));
    }
  });
}

см. Следующий рабочий фрагмент ...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable({
    "cols": [
      {"label": "id", "type": "string"},
      {"label": "x", "type": "number"},
      {"label": "y", "type": "number"}
    ],
    "rows": [
      {"c":[{"v": ""}, {"v": 2015}, {"v": 1}]},
      {"c":[{"v": ""}, {"v": 2016}, {"v": 2}]},
      {"c":[{"v": ""}, {"v": 2017}, {"v": 3}]},
      {"c":[{"v": ""}, {"v": 2018}, {"v": 4}]},
      {"c":[{"v": ""}, {"v": 2019}, {"v": 5}]},
      {"c":[{"v": ""}, {"v": 2020}, {"v": 6}]}
    ]
  });

  var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));

  google.visualization.events.addListener(chart, 'ready', moveYAxisLabels);
  google.visualization.events.addListener(chart, 'animationfinish', moveYAxisLabels);

  function moveYAxisLabels() {
    var chartLayout = chart.getChartLayoutInterface();
    var labels = chart.getContainer().getElementsByTagName('text');
    var labelIndex = -1;
    Array.prototype.forEach.call(labels, function(label) {
      if (label.getAttribute('text-anchor') === 'end') {
        labelIndex++;
        labelHeight = chartLayout.getBoundingBox('vAxis#0#label#' + labelIndex).height;
        labelBottom = chartLayout.getBoundingBox('vAxis#0#gridline#' + labelIndex).top;
        labelTop = chartLayout.getBoundingBox('vAxis#0#gridline#' + (labelIndex + 1)).top;
        label.setAttribute('y', labelBottom - ((labelBottom - labelTop) / 2) + Math.floor(labelHeight / 2));
      }
    });
  }

  var options = {
    sizeAxis: {
      maxSize: 7,
      minSize: 1
    },
    animation: {
      duration: 1500,
      easing: 'in',
      startup: true
    },
    fontSize: 10,
    legend: 'none',
    height: 230,
    chartArea: {
      bottom: 48,
      left: 200,
      right: 18,
      top: 18,
      width: '100%',
      height: '100%'
    },
    bubble: { stroke: '#ffca18', opacity: 1 },
    colors: ['#ffca18', '#ffca18'],
    tooltip: {
      trigger: 'none'
    },
    hAxis: {
      ticks: [
        { v: 2015, f: '2015' },
        { v: 2016, f: '2016' },
        { v: 2017, f: '2017' },
        { v: 2018, f: '2018' },
        { v: 2019, f: '2019' },
        { v: 2020, f: '2020' }
      ],
      gridlines: { color: '#dedede' },
      minorGridlines: { color: '#f7f7f7', count: 3 },
      textStyle: { color: '#5f5f5f' }
    },
    vAxis: {
      ticks: [
        { v: 1, f: 'JUNE' },
        { v: 2, f: 'MAY' },
        { v: 3, f: 'APRIL' },
        { v: 4, f: 'MARCH' },
        { v: 5, f: 'FEBRUARY' },
        { v: 6, f: 'JANUARY' },
        { v: 7, f: '' }
      ],
      gridlines: { color: '#dedede' },
      textStyle: { color: '#5f5f5f' },
      viewWindowMode: 'explicit',
      viewWindow: {
        min: 1,
        max: 7
      }
    }
  };

  chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Единственная проблема здесь - анимация,
график переместит метки на 'ready',
, затем мы переместим их обратно на 'animationfinish',
поэтому они кажутся прыгающими.
Вы можете переосмыслить, используя анимацию ...

...