如何在jqplot饼图上显示工具提示

How to display tooltips on jqplot pie chart

本文关键字:显示 工具提示 jqplot      更新时间:2023-09-26

我有一个带有图例的jqplot饼图,我想让图例文本在鼠标悬停在饼上时显示为工具提示。我不知道该怎么做。有人有类似的经验吗?

示例代码:

$(document).ready(function(){
  var data = [['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],['Out of home', 16],['Commuting', 7], ['Orientation', 9]];
  var plot1 = jQuery.jqplot ('chart1', [data],
    {
      seriesDefaults: {
        renderer: jQuery.jqplot.PieRenderer,
        rendererOptions: {
          showDataLabels: true
        }
      },
      legend: { show:true, location: 'e' }
    }
  );
});

我使用的是最新版本的jqPlot,并通过在"seriesDefaults"部分中使用以下内容来获得工具提示:

highlighter: {
  show: true,
  formatString:'%s', 
  tooltipLocation:'sw', 
  useAxesFormatters:false
}

重要的部分是"useAxesFormatters: false",因为饼图中没有轴。您可以随意更改"formatString"为您想要的任何内容,但对我来说,只是"%s"显示的是与图例中显示的完全相同的字符串。

您需要绑定jqplot数据高亮显示和取消高亮显示事件,获取您想要显示的数据并设置包含div标题属性的图表。

下面的代码显示了"x: y"格式的标题,其中x是图例标签,y是值:

 var plot = $.jqplot('plotDivId',...);
 $("#plotDivId").bind('jqplotDataHighlight', function(ev, seriesIndex, pointIndex, data) {
            var $this = $(this);                
            $this.attr('title', data[0] + ": " + data[1]);                               
        }); 
 $("#plotDivId").bind('jqplotDataUnhighlight', function(ev, seriesIndex, pointIndex, data) {
            var $this = $(this);                
            $this.attr('title',""); 
 });

这段代码正在我的系统中使用,运行正常

我在以下链接上使用的是荧光笔插件的版本:

https://github.com/tryolabs/jqplot-highlighter

我使用的参数:

highlighter: {
    show:true,
    tooltipLocation: 'n',
    tooltipAxes: 'pieref', // exclusive to this version
    tooltipAxisX: 20, // exclusive to this version
    tooltipAxisY: 20, // exclusive to this version
    useAxesFormatters: false,
    formatString:'%s, %P',
}

新参数确保工具提示出现的固定位置。我更喜欢把它放在左上角,以避免在调整容器div大小时出现问题。

我不相信这是内置的。您需要将处理程序绑定到'jqplotDataHighlight'和'jqplotDataUnhighlight'事件。请参阅本页底部的示例。这是对气泡图的处理,但它也应该转化为饼图。

由于我无法让荧光笔工作-它在饼图上没有为我显示任何内容-我最终采用了基于荧光笔事件显示浏览器工具提示的解决方案。

var plot1 = jQuery.jqplot ('chart1', [data], {
seriesDefaults: {
    renderer: jQuery.jqplot.PieRenderer
    }
}
);
$('#chart1').bind('jqplotDataHighlight', function (ev, seriesIndex, pointIndex, data) { 
    document.getElementById('chart1').title = data;
    //alert('series: '+seriesIndex+', point: '+pointIndex+', data: '+data);
    });