JFreechart: display X axis with values ​​after certain units

I am using jfreechart to display a line graph. Now on the x-axis, it shows the value for each pair (x, y) in the diagram. As a result, the X axis has a huge amount of overlapping values. I want to show a few for example, after every 5 units or something like that. How is this possible using Jfreechart.

+3
source share
1 answer

Before a NumberAxisgraphic is drawn, its labels will be updated. The result is Listthat which includes an object NumberTickfor each axis mark mark.

By overriding a function NumberAxis.refreshTicks, you can control how labels are displayed.

, , TickType.MAJOR. 5, .

, 5, .

XYPlot plot = (XYPlot) chart.getPlot();

NumberAxis myAxis = new NumberAxis(plot.getDomainAxis().getLabel()) {
  @Override
  public List refreshTicks(Graphics2D g2, AxisState state,
                           Rectangle2D dataArea, RectangleEdge edge) {

    List allTicks = super.refreshTicks(g2, state, dataArea, edge);
    List myTicks = new ArrayList();

    for (Object tick : allTicks) {
      NumberTick numberTick = (NumberTick) tick;

      if (TickType.MAJOR.equals(numberTick.getTickType()) &&
                    (numberTick.getValue() % 5 != 0)) {
        myTicks.add(new NumberTick(TickType.MINOR, numberTick.getValue(), "",
                    numberTick.getTextAnchor(), numberTick.getRotationAnchor(),
                    numberTick.getAngle()));
        continue;
      }
      myTicks.add(tick);
    }
    return myTicks;
  }
};

plot.setDomainAxis(myAxis);
+3

All Articles