3
votes

I am using jfreechart for displaying line graph.Now, on X axis it shows value for every (x,y) pair on chart.As a result the X axis has huge amount of values getting overlapped.I want to display few values eg after every 5 units or something like that.How is this possible using Jfreechart.

1
Please edit your question to include an sscce that exhibits the problem and shows what you've tried.trashgod

1 Answers

3
votes

Before the NumberAxis of the chart's plot is drawn, its tick marks are refreshed. The result is a List that includes a NumberTick object for each tick mark of the axis.

By overriding the function NumberAxis.refreshTicks you can control how and if the marks will be shown.

For example, in the following code I get all tick marks and iterate through them looking for TickType.MAJOR. If the value of a major tick mark is not dividable by 5, it gets replaced by a minor tick mark.

As a result, only values dividable by 5 will be shown with their text label.

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