Настройка точек

Обзор

Во многих диаграммах Google значения данных отображаются в точных точках. Линейная диаграмма — это просто набор этих точек, соединенных линиями, а точечная диаграмма — не что иное, как точки.

На всех диаграммах, кроме точечной, эти точки по умолчанию имеют нулевой размер. Вы можете контролировать их размер с помощью параметра pointSize и их форму с помощью параметра pointShape .

Выше вы можете увидеть диаграмму с шестью рядами, каждый с pointSize 30, но с другим pointShape .

Опции
        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 7 },
          pointSize: 30,
          series: {
                0: { pointShape: 'circle' },
                1: { pointShape: 'triangle' },
                2: { pointShape: 'square' },
                3: { pointShape: 'diamond' },
                4: { pointShape: 'star' },
                5: { pointShape: 'polygon' }
            }
        };
Полный HTML
  <head>
    <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);
      function drawChart() {
        var data = google.visualization.arrayToDataTable
            ([['X', '1', '2', '3', '4', '5', '6'],
              [1, 2, null, null, null, null, null],
              [2, null, 3, null, null, null, null],
              [3, null, null, 4, null, null, null],
              [4, null, null, null, 5, null, null],
              [5, null, null, null, null, 6, null],
              [6, null, null, null, null, null, 7]
        ]);

        var options = {
          legend: 'none',
          pointSize: 30,
          series: {
                0: { pointShape: 'circle' },
                1: { pointShape: 'triangle' },
                2: { pointShape: 'square' },
                3: { pointShape: 'diamond' },
                4: { pointShape: 'star' },
                5: { pointShape: 'polygon' }
            }
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Несколько простых примеров

В отличие от диаграммы в предыдущем разделе, большинство диаграмм имеют только одну серию. Вот пример линейного графика с круглыми точками размером 20 pt:

Поскольку pointShape по умолчанию — это круг, мы можем не указывать его в параметрах:

Опции
        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          curveType: 'function',
          pointSize: 20,
      };
Полный HTML
  <head>
    <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);
      function drawChart() {
        var data = google.visualization.arrayToDataTable
            ([['X', 'Y'],
              [1, 3],
              [2, 2.5],
              [3, 3],
              [4, 4],
              [5, 4],
              [6, 3],
              [7, 2.5],
              [8, 3]
        ]);

        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          curveType: 'function',
          pointSize: 20,
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Вы можете изменить его с «круг» на другую форму, установив для pointShape значение «треугольник», «квадрат», «ромб», «звезда» или «многоугольник»:

Опции
        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          colors: ['#795548'],
          pointSize: 20,
          pointShape: 'square'
        };
Полный HTML
  <head>
    <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);
      function drawChart() {
        var data = google.visualization.arrayToDataTable
            ([['X', 'Y'],
              [1, 3],
              [2, 2.5],
              [3, 3],
              [4, 4],
              [5, 4],
              [6, 3],
              [7, 2.5],
              [8, 3]
        ]);

        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          colors: ['#795548'],
          pointSize: 20,
          pointShape: 'square'
       };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Формы «звезда» и «многоугольник» позволяют настроить количество сторон, по умолчанию у обеих сторон пять. Некоторые четырехсторонние звезды:

Опции
        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          colors: ['#EF851C'],
          pointSize: 30,
          pointShape: { type: 'star', sides: 4 }
        };
Полный HTML
<html>
  <head>
    <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);
      function drawChart() {
        var data = google.visualization.arrayToDataTable
            ([['X', 'Y'],
              [1, 3],
              [2, 2.5],
              [3, 3],
              [4, 4],
              [5, 4],
              [6, 3],
              [7, 2.5],
              [8, 3]
        ]);

        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          colors: ['#EF851C'],
          pointSize: 30,
          pointShape: { type: 'star', sides: 4 }
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Звезды можно дополнительно настроить с помощью параметра dent , который определяет, насколько вогнута звезда. Когда вмятина близка к нулю, звезда будет похожа на морскую звезду; по мере того, как вмятина приближается к ней, она выходит за пределы равностороннего многоугольника.

Вот вмятины от 0,05 до 0,8 для пятисторонних звезд:

Опции
var options = {
    legend: 'none',
    hAxis: { textPosition: 'none' },
    vAxis: { textPosition: 'none', gridlines: { count: 0 },
	     baselineColor: 'white' },
    colors: ['#E94D20', '#ECA403', '#63A74A',
	     '#15A0C8', '#4151A3', '#703593', '#981B48'],
    pointSize: 20,
    annotations: { stemColor: 'white', textStyle: { fontSize: 16 } },
    series: {
	0: { pointShape: { type: 'star', sides: 5, dent: 0.05 } },
	1: { pointShape: { type: 'star', sides: 5, dent: 0.1 } },
	2: { pointShape: { type: 'star', sides: 5, dent: 0.2 } },
	3: { pointShape: { type: 'star', sides: 5 } },
	4: { pointShape: { type: 'star', sides: 5, dent: 0.5 } },
	5: { pointShape: { type: 'star', sides: 5, dent: 0.7 } },
	6: { pointShape: { type: 'star', sides: 5, dent: 0.8 } },
    }
};
Полный HTML
<html>
  <head>
    <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);
      function drawChart() {
	  var data = new google.visualization.DataTable();
	  data.addColumn('string', 'Element');
	  data.addColumn('number', 'A');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addColumn('number', 'B');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addColumn('number', 'C');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addColumn('number', 'D');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addColumn('number', 'E');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addColumn('number', 'F');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addColumn('number', 'G');
	  data.addColumn( { type: 'string', role: 'annotation' });
	  data.addRow(['A', 1, "dent: 0.05", , , , , , , , , , , , null]);
	  data.addRow(['B', , , 1, "dent: 0.1", , , , , , , , , , null]);
	  data.addRow(['C', , , , , 1, "dent: 0.2", , , , , , , , null]);
	  data.addRow(['D', , , , , , , 1, "default", , , , , , null]);
	  data.addRow(['E', , , , , , , , , 1, "dent: 0.5", , , , null]);
	  data.addRow(['F', , , , , , , , , , , 1, "dent: 0.7", , null]);
	  data.addRow(['G', , , , , , , , , , , , , 1, "dent: 0.8"]);

	  var options = {
              legend: 'none',
	      hAxis: { textPosition: 'none' },
              vAxis: { textPosition: 'none', gridlines: { count: 0 },
		       baselineColor: 'white' },
              colors: ['#E94D20', '#ECA403', '#63A74A',
		       '#15A0C8', '#4151A3', '#703593', '#981B48'],
              pointSize: 20,
              annotations: { stemColor: 'white', textStyle: { fontSize: 16 } },
              series: {
		  0: { pointShape: { type: 'star', sides: 5, dent: 0.05 } },
		  1: { pointShape: { type: 'star', sides: 5, dent: 0.1 } },
		  2: { pointShape: { type: 'star', sides: 5, dent: 0.2 } },
		  3: { pointShape: { type: 'star', sides: 5 } },
		  4: { pointShape: { type: 'star', sides: 5, dent: 0.5 } },
		  5: { pointShape: { type: 'star', sides: 5, dent: 0.7 } },
		  6: { pointShape: { type: 'star', sides: 5, dent: 0.8 } },
              }
          };

          var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
          chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Вращения

Все формы точек можно вращать с помощью опции rotation , указанной в градусах. Например, мы можем сделать наши треугольники направленными вниз на следующей диаграмме с областями, повернув их на 180 градусов:

Опции
        var options = {
          legend: 'none',
          colors: ['#15A0C8'],
          pointSize: 30,
          pointShape: { type: 'triangle', rotation: 180 }
        };
Полный HTML
  <head>
    <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);
      function drawChart() {
        var data = google.visualization.arrayToDataTable
            ([['X', 'Y'],
              [1, 3],
              [2, 2.5],
              [3, 2],
              [4, 3],
              [5, 4.5],
              [6, 6.5],
              [7, 9],
              [8, 12]
        ]);

        var options = {
          legend: 'none',
          colors: ['#15A0C8'],
          pointSize: 30,
          pointShape: { type: 'triangle', rotation: 180 }
        };

        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Настройка отдельных точек

По умолчанию стили, примененные к точке, применяются ко всем точкам в серии. Если вы хотите изменить внешний вид определенной точки данных, вы можете сделать это, настроив ее.

На следующем графике мы увеличиваем размер одной из точек, уменьшаем непрозрачность до 0,3 и меняем форму и цвет:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable ([['X', 'Y', {'type': 'string', 'role': 'style'}], [1, 3, null], [2, 2.5, null], [3, 3, null], [4, 4, null], [5, 4, null], [6, 3, 'point { size: 18; shape-type: star; fill-color: #a52714; }'], [7, 2.5, null], [8, 3, null] ]); var options = { legend: 'none', hAxis: { minValue: 0, maxValue: 9 }, curveType: 'function', pointSize: 7, dataOpacity: 0.3 }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable ([['X', 'Y', {'type': 'string', 'role': 'style'}], [1, 3, null], [2, 2.5, null], [3, 3, null], [4, 4, null], [5, 4, null], [6, 3, 'point { size: 18; shape-type: star; fill-color: #a52714; }'], [7, 2.5, null], [8, 3, null] ]); var options = { legend: 'none', hAxis: { minValue: 0, maxValue: 9 }, curveType: 'function', pointSize: 7, dataOpacity: 0.3 }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); }
<html>
  <head>
    <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);

      function drawChart() {
        var data = google.visualization.arrayToDataTable
            ([['X', 'Y', {'type': 'string', 'role': 'style'}],
              [1, 3, null],
              [2, 2.5, null],
              [3, 3, null],
              [4, 4, null],
              [5, 4, null],
              [6, 3, 'point { size: 18; shape-type: star; fill-color: #a52714; }'],
              [7, 2.5, null],
              [8, 3, null]
        ]);

        var options = {
          legend: 'none',
          hAxis: { minValue: 0, maxValue: 9 },
          curveType: 'function',
          pointSize: 7,
          dataOpacity: 0.3
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Доступны следующие настройки стиля:

  • fill-color (указывается в виде шестнадцатеричной строки.)
  • shape-dent
  • shape-rotation
  • shape-sides
  • shape-type
  • stroke-color (указывается в виде шестнадцатеричной строки.)
  • stroke-width (указывается в виде шестнадцатеричной строки.)
  • size
  • visible (Видна ли точка или нет.)

Непрозрачность регулируется не стилем, а опцией dataOpacity .