Search code examples
jsfprimefacesjqplot

Dynamically display the x-axis labels in the datatip of p:chart (bar)


Using PrimeFaces p:chart, is it possible to dynamically display x-axis labels in the datatip of bar chart instead of the 'index' in the series?

For example, if I have the following code:

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

And

@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;
  }
}

The datatip will show (1,1222) and (2,3323). Can I have them shown as (car,1222) and (bus,3323)? Moreover I would like to have them to be dynamically updated with the bar model. i.e. if another point is added like chartSeries.set("train",4455), the datatip should also be updated accordingly.

I am using Java 8, JSF2.2 and Primefaces 6.2.


Solution

  • After spending a long time to investigate the jqplot structure, I finally find the answer:

    Java code:

    @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 page:

    <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>
    

    and JavaScript function:

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