将HTML添加到Google折线图工具提示 [英] Add HTML to Google Line Chart tool tip

查看:69
本文介绍了将HTML添加到Google折线图工具提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在Cats折线图的工具提示上添加一条线.

I want to add a line on tooltip of Cats line chart.

注意:我的笔记在这里.

Note: My note goes here..

现在,当我们将猫的图表悬停时,我们可以看到类似的

Now when we hover cats chart,we can see like

2020年1月1日

Jan 1, 2020

猫:10%,百分比:0%

Cats:10, percent: 0%

在此行下方,我要添加注释行(与其他工具提示相比,该行为灰色,并且字体大小减小了).因此,工具提示将如下所示:

Below this line I want to add the Note line (in grey color and reduced font-size than other tooltip). So the tooltip will look like:

2020年1月1日

Jan 1, 2020

猫:10%,百分比:0%

Cats:10, percent: 0%

注意:我的笔记在这里.

Note: My note goes here..

以下是我的图表代码:

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

function prepareChartData(){
  var chartData = new google.visualization.DataTable();
  chartData.addColumn('date', 'Date');
  chartData.addColumn('number', 'Total');
  chartData.addColumn('number', 'Dogs');
  chartData.addColumn('number', 'Cats');
  title = 'My Chart';

  var options = {
title: title,
curveType: 'function',
legend: {position: 'bottom', alignment: 'start'},
colors: ['#003f5c', '#ffa600', '#665191', '#f95d6a'],
chartArea: {
	bottom: 80
},
annotations: {
  alwaysOutside: true,
  textStyle: {
    color: 'black',
    fontSize: 11
  },
},
hAxis: {
  format: 'MMM yy',
  viewWindowMode: "explicit",
},
vAxis: {
  minValue: 0,
  viewWindowMode: "explicit",
  viewWindow: { min: 0 },
  title: ''
},
titleTextStyle: {
  color:'#3a3a3a',
  fontSize:24,
  bold:false
  // fontName: "Segoe UI"
  },
bar: {groupWidth: '95%'},
bars: 'horizontal'
  };

  var chartDivId = "chart_div";
  var chart = new google.visualization.LineChart(document.getElementById(chartDivId));
  var rawData =[];

   var chart_object = { "Dec 19": {monthLabel: "Dec", chartArray:[{'date': "2019-12-31", 'total': "5", 'cats': "10 \n <b>Test</b>", 'dogs': "10"}]},"Jan 20": {monthLabel: "Jan", chartArray:[{'date': "2020-1-01", 'total': "5", 'cats': "10", 'dogs': "10"}]},"Feb 20": {monthLabel: "Feb", chartArray:[{'date': "2020-2-29", 'total': "5", 'cats': "10", 'dogs': "10"}]}, "Mar 20": {monthLabel: "Mar", chartArray:[{'date': "2020-3-01", 'total': "5", 'cats': "10", 'dogs': "10"},{'date': "2020-03-12", 'total': "15", 'cats': "30", 'dogs': "30"}]}};

  $.each(chart_object, function(i, chartobject) {
 	$.each(  chartobject.chartArray, function( chartIndex , chartValue ){

date = chartValue['date'];
total = parseInt(chartValue['total']);
catscount = parseInt(chartValue['cats']);
dogscount = parseInt(chartValue['dogs']);
catspercentage = 0;
catspercentageAnnotation = catscount+",  percent "+catspercentage+"%";
dogsspercentage = 0;
dogsspercentageAnnotation = dogscount+",  percent "+dogsspercentage+"%";

rawData.push([ new Date(date), total, {v: catscount, f: catspercentageAnnotation}, {v: dogscount, f: dogsspercentageAnnotation}]);
  });
  });

  var counter = 0;
  drawChart();

  function drawChart() {
if(counter < rawData.length){
  chartData.addRow(rawData[counter]);

  // build x-axis ticks to prevent repeated labels
  var dateFormat = new google.visualization.DateFormat({
    pattern: 'yyyy-MM-dd'
  });
  var dateRange = chartData.getColumnRange(0);
  var ticks = [];
  var dateTick = dateRange.min;
  while (dateTick.getTime() <= dateRange.max.getTime()) {
    if (ticks.length === 0) {
      // format first tick
      ticks.push({
        v: dateTick,
        f: dateFormat.formatValue(dateTick)
      });
    } else {
      ticks.push(dateTick);
    }
    dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 1, 1);
  }
  options.hAxis.ticks = ticks;

  chart.draw(chartData, options);
  counter++;
  window.setTimeout(drawChart, 1000);
}
  }
}

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript" ></script>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <div id="chart_div"></div>

如何添加html代码/css样式来实现这一目标?

How can I add html code/css styles to achieve this?

有人可以帮助我做到这一点吗?预先感谢.

Can anyone help me to do this? Thanks in advance.

推荐答案

没有可用于向工具提示添加内容的标准选项.
相反,您可以使用工具提示列角色提供自定义工具提示.
但这确实意味着您将必须提供工具提示的全部内容.

there are no standard options you can use to add content to the tooltip.
instead, you can use the tooltip column role to provide a custom tooltip.
but this does mean you will have to provide the entire content of the tooltip.

工具提示列角色应作为数据表中的另一列添加.
并且应该遵循它所代表的系列列.
在这里,工具提示列添加在cats列之后.

the tooltip column role should be added as another column in the data table.
and it should follow the series column it represents.
here, the tooltip column is added after the cats column.

  var chartData = new google.visualization.DataTable();
  chartData.addColumn('date', 'Date');
  chartData.addColumn('number', 'Total');
  chartData.addColumn('number', 'Dogs');
  chartData.addColumn('number', 'Cats');
  chartData.addColumn({role: 'tooltip', type: 'string', p: {html: true}});

如果要为狗或整个系列创建自定义工具提示,
您只需在每个之后添加另一个工具提示列.

if you want a custom tooltip for the dogs or total series,
you would just add another tooltip column after each.

  var chartData = new google.visualization.DataTable();
  chartData.addColumn('date', 'Date');
  chartData.addColumn('number', 'Total');
  chartData.addColumn({role: 'tooltip', type: 'string', p: {html: true}});
  chartData.addColumn('number', 'Dogs');
  chartData.addColumn({role: 'tooltip', type: 'string', p: {html: true}});
  chartData.addColumn('number', 'Cats');
  chartData.addColumn({role: 'tooltip', type: 'string', p: {html: true}});

如您在上面看到的,为了获得html工具提示,
该列确实需要特殊属性-> p:{html:true}

as you can see above, in order to have html tooltips,
the column does require a special property --> p: {html: true}

,我们还必须添加一个工具提示配置选项...

and we must also add a tooltip config option...

tooltip: {
  isHtml: true
}

然后我们可以构建工具提示内容,
以及其余的数据行...

then we can build the tooltip content,
along with the rest of the data rows...

  var tooltip = '<div class="ggl-tooltip">';
  tooltip += '<div><span>' + formatDate.formatValue(date) + '</span></div>';
  tooltip += '<div>' + chartData.getColumnLabel(3) + ': ';
  tooltip += '<span>' + catspercentageAnnotation + '</span></div>';
  tooltip += '<div>Note: My note goes here..</div></div>';

  rawData.push([date, total, {v: dogscount, f: dogsspercentageAnnotation}, {v: catscount, f: catspercentageAnnotation}, tooltip]);

,并且当工具提示显示在图表中时,
我们可以使用CSS设置工具提示的样式...

and when the tooltip is shown in the chart,
we can use CSS to style the tooltip...

.ggl-tooltip {
  border: 1px solid #e0e0e0;
  font-family: Segoe UI;
  font-size: 12pt;
  padding: 8px 8px 8px 8px;
}

.ggl-tooltip span {
  font-weight: bold;
}

.ggl-tooltip div {
  padding: 4px 4px 4px 4px;
}

有关示例,请参见以下工作片段

see following working snippet for an example...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var chartData = new google.visualization.DataTable();
  chartData.addColumn('date', 'Date');
  chartData.addColumn('number', 'Total');
  chartData.addColumn('number', 'Dogs');
  chartData.addColumn('number', 'Cats');
  chartData.addColumn({role: 'tooltip', type: 'string', p: {html: true}});
  title = 'My Chart';

  var options = {
    title: title,
    curveType: 'function',
    legend: {position: 'bottom', alignment: 'start'},
    colors: ['#003f5c', '#ffa600', '#665191', '#f95d6a'],
    chartArea: {
      bottom: 80
    },
    annotations: {
      alwaysOutside: true,
      textStyle: {
        color: 'black',
        fontSize: 11
      },
    },
    hAxis: {
      format: 'MMM yy',
      viewWindowMode: "explicit",
    },
    vAxis: {
      minValue: 0,
      viewWindowMode: 'explicit',
      viewWindow: { min: 0 },
      title: ''
    },
    titleTextStyle: {
      color: '#3a3a3a',
      fontSize: 24,
      bold: false
    },
    bar: {groupWidth: '95%'},
    bars: 'horizontal',

    fontName: 'Segoe UI',
    tooltip: {
      isHtml: true
    }
  };

  var chartDivId = "chart_div";
  var chart = new google.visualization.LineChart(document.getElementById(chartDivId));
  var formatDate = new google.visualization.DateFormat({
    pattern: 'MMM d, yyyy'
  });
  var rawData =[];

  var chart_object = { "Dec 19": {monthLabel: "Dec", chartArray:[{'date': "2019-12-31", 'total': "5", 'cats': "10 \n <b>Test</b>", 'dogs': "10"}]},"Jan 20": {monthLabel: "Jan", chartArray:[{'date': "2020-1-01", 'total': "5", 'cats': "10", 'dogs': "10"}]},"Feb 20": {monthLabel: "Feb", chartArray:[{'date': "2020-2-29", 'total': "5", 'cats': "10", 'dogs': "10"}]}, "Mar 20": {monthLabel: "Mar", chartArray:[{'date': "2020-3-01", 'total': "5", 'cats': "10", 'dogs': "10"},{'date': "2020-03-12", 'total': "15", 'cats': "30", 'dogs': "30"}]}};

  $.each(chart_object, function(i, chartobject) {
    $.each(chartobject.chartArray, function(chartIndex, chartValue){
      date = new Date(chartValue['date']);
      total = parseInt(chartValue['total']);
      catscount = parseInt(chartValue['cats']);
      dogscount = parseInt(chartValue['dogs']);
      catspercentage = 0;
      catspercentageAnnotation = catscount+",  percent "+catspercentage+"%";
      dogsspercentage = 0;
      dogsspercentageAnnotation = dogscount+",  percent "+dogsspercentage+"%";

      var tooltip = '<div class="ggl-tooltip">';
      tooltip += '<div><span>' + formatDate.formatValue(date) + '</span></div>';
      tooltip += '<div>' + chartData.getColumnLabel(3) + ': ';
      tooltip += '<span>' + catspercentageAnnotation + '</span></div>';
      tooltip += '<div>Note: My note goes here..</div></div>';

      rawData.push([date, total, {v: dogscount, f: dogsspercentageAnnotation}, {v: catscount, f: catspercentageAnnotation}, tooltip]);
    });
  });

  var counter = 0;
  drawChart();

  function drawChart() {
    if (counter < rawData.length) {
      chartData.addRow(rawData[counter]);
      var dateFormat = new google.visualization.DateFormat({
        pattern: 'yyyy-MM-dd'
      });
      var dateRange = chartData.getColumnRange(0);
      var ticks = [];
      var dateTick = dateRange.min;
      while (dateTick.getTime() <= dateRange.max.getTime()) {
        if (ticks.length === 0) {
          ticks.push({
            v: dateTick,
            f: dateFormat.formatValue(dateTick)
          });
        } else {
          ticks.push(dateTick);
        }
        dateTick = new Date(dateTick.getFullYear(), dateTick.getMonth() + 1, 1);
      }
      options.hAxis.ticks = ticks;

      chart.draw(chartData, options);
      counter++;
      window.setTimeout(drawChart, 1000);
    }
  }
});

.ggl-tooltip {
  border: 1px solid #e0e0e0;
  font-family: Segoe UI;
  font-size: 10pt;
  padding: 8px 8px 8px 8px;
}

.ggl-tooltip span {
  font-weight: bold;
}

.ggl-tooltip div {
  padding: 4px 4px 4px 4px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

这篇关于将HTML添加到Google折线图工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆