首页 > 解决方案 > 在 p:chart (bar) 的 datatip 中动态显示 x 轴标签

问题描述

使用 PrimeFaces p:chart,是否可以在条形图的数据提示中动态显示 x 轴标签,而不是系列中的“索引”?

例如,如果我有以下代码:

<h:body>                                 
   <p:chart type="bar" model="#{barChartDatatipView.barChartModel}" />                                                                        
</h:body>

@ManagedBean
@ViewScoped
public class BarChartDatatipView {

  public BarChartModel getBarChartModel() {

    BarChartModel model = new BarChartModel();
    ChartSeries chartSeries = new BarChartSeries();
    chartSeries.set("car", 1222);
    chartSeries.set("bus", 3323); 
    model.addSeries(chartSeries);
    return model;
  }
}

数据提示将显示 (1,1222) 和 (2,3323)。我可以将它们显示为 (car,1222) 和 (bus,3323) 吗?此外,我想让它们使用条形模型动态更新。即,如果添加另一个点,如 chartSeries.set("train",4455),则数据提示也应相应更新。

我正在使用 Java 8、JSF2.2 和 Primefaces 6.2。

标签: jsfprimefacesjqplot

解决方案


查了好久jqplot结构,终于找到了答案:

Java代码:

@ManagedBean
@ViewScoped
public class BarChartDatatipView {

  public BarChartModel getBarChartModel() {

    BarChartModel model = new BarChartModel();
    ChartSeries chartSeries = new BarChartSeries();
    chartSeries.set("car", 1222);
    chartSeries.set("bus", 3323); 
    model.addSeries(chartSeries);
    model.setDatatipEditor("tooltipContentEditor");  // Set the editor.
    return model;
  }
}

HTML页面:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:p="http://primefaces.org/ui">

  <h:head>
    <title>Bar Chart - datatip</title>
    <h:outputScript name="js/barchart-datatip.js" />   
  </h:head>
  <h:body>                                                 
    <p:chart type="bar" model="#{barChartDatatipView.barChartModel}" />                                                                        
  </h:body>
</html>

和 JavaScript 函数:

function tooltipContentEditor(str, seriesIndex, pointIndex, plot) {
    return plot.axes.xaxis.ticks[pointIndex] + ", " + plot.data[seriesIndex][pointIndex];
}

推荐阅读