1

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.

cbangor
  • 140
  • 1
  • 12
  • PrimeFaces p:chart uses jqplot. The duplicate shows how to do it in there and combine this with using the PrimeFaces `p:chart` extender functionality – Kukeltje Sep 14 '18 at 14:03
  • Possible duplicate of [jqplot tooltip on bar chart](https://stackoverflow.com/questions/4889464/jqplot-tooltip-on-bar-chart) – Kukeltje Sep 14 '18 at 14:04
  • @Kukeltje Thank you for your comments. I have tried the JS function in the link but only managed to get [null, 1222] displayed. I will try to use the extender later. – cbangor Sep 19 '18 at 07:41

1 Answers1

0

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];
}
cbangor
  • 140
  • 1
  • 12