Search code examples
javajfreechartlinechart

JFreeChart displaying three dots (...) in place of the values on the X axis


I am trying to plot a simple line chart and almost everything is fine, I am populating my dataset with a simple code like this:

DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(-10 , "S21" , "1000" );
dataset.addValue(-20 , "S21" , "1001" );
dataset.addValue(-25 , "S21" , "1002" );
dataset.addValue(-30 , "S21" , "1003" );
dataset.addValue(-25 , "S21" , "1004" );
...

then I create a line chart:

lineChart = ChartFactory.createLineChart(
    "S21",
    "Frequency (MHz)",
    "Value (db)",
    dataset,
    PlotOrientation.VERTICAL,
    true,
    true,
    false);

and I have on the X axis the values 1000 1001 1002 ... etc. Anyway I noticed that, if I add some more points, jfreechart does not have enough space on the x axis and displays three dots (...) in the place of the values. This is pretty weird, I would like to have as many points as I like (e.g. 1000, to have a good resolution) but the labels shown only for a subset of these points, so I do not run out od space:

E.g. points: 1000, 1001, 1002, ..., 2000 (1000 points)

Labels: 1000, 1100, 1200, ..., 1900, 2000 (10 labels)

Is it possible? I looked for a solution on the net, but didn't find anything useful.


Solution

  • You may have to combine several approaches:

    • Alter the CategoryLabelPositions as suggested here.

      CategoryAxis domainAxis = plot.getDomainAxis();
      domainAxis.setCategoryLabelPositions(
          CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2.0));
      
    • Adjust the chart's size, as suggested here.

      ChartPanel piePanel = new ChartPanel(lineChart) {
          @Override
          public Dimension getPreferredSize() {
              return new Dimension(640, 480);
          }
      };
      
    • Optionally, depending on the number of categories, use a SlidingCategoryDataset, as suggested here.

    • Optionally, if the categories form a continuous domain, switch to an XY plot, e.g. ChartFactory.createXYLineChart().

    image