How to add a simple horizontal line at Y value of JFreeChart TimeSeries

1.3k views Asked by At

I have created a chart like so:

enter image description here

Main code used for adding and/or updating information:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
Date date = simpleDateFormat.parse(dateAsStringToParse);
Second second = new Second(date);
myInfo.getSeries().addOrUpdate(second, maxValue); // maxValue is an Integer

And for creation of actual chart:

final XYDataset dataset = new TimeSeriesCollection(myInfo.getSeries());
JFreeChart timechart = ChartFactory.createTimeSeriesChart(myInfo.getName()
    + " HPS", "", "HPS", dataset, false, false, false);

I would like to simply add an horizontal line (parallel to X (time) axis) at a constant value, let's say 10,000. So the graph will look something like so:

enter image description here

What would be the easiest (most correct) way to achieve this with my code?

1

There are 1 answers

0
trashgod On BEST ANSWER

It looks like you want an XYLineAnnotation, but the coordinates for a TimeSeries may be troublesome. Starting from TimeSeriesChartDemo1, I made the following changes to get the chart shown.

  1. First, we need the x value for the first and last RegularTimePeriod in the TimeSeries.

     long x1, x2;
     …
     x1 = s1.getTimePeriod(0).getFirstMillisecond();
     x2 = s1.getNextTimePeriod().getLastMillisecond();
    
  2. Then, the constant y value is easy; I chose 140.

     double y = 140;
    

    Alternatively, you can derive a value from your TimeSeries, for example.

     double y = s1.getMinY() + ((s1.getMaxY() - s1.getMinY()) / 2);
    
  3. Finally, we construct the annotation and add it to the plot.

     XYLineAnnotation line = new XYLineAnnotation(
         x1, y, x2, y, new BasicStroke(2.0f), Color.black);
     plot.addAnnotation(line);
    

image