如何在 JFreeChart TimeSeries 的 Y 值处添加一条简单的水平线

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

我创建了一个这样的图表:

用于添加and/or更新信息的主要代码:

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

以及创建实际图表:

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

我想简单地添加一条水平线(平行于 X(时间)轴)在一个常数值,比方说 10,000。所以图表看起来像这样:

用我的代码实现这个最简单(最正确)的方法是什么?

您似乎想要一个 XYLineAnnotation, but the coordinates for a TimeSeries may be troublesome. Starting from TimeSeriesChartDemo1,我进行了以下更改以显示图表。

  1. 首先,我们需要 TimeSeries 中第一个和最后一个 RegularTimePeriodx 值。

     long x1, x2;
     …
     x1 = s1.getTimePeriod(0).getFirstMillisecond();
     x2 = s1.getNextTimePeriod().getLastMillisecond();
    
  2. 那么,常数y值就容易了;我选择了140.

     double y = 140;
    

    或者,您可以从 TimeSeries 中导出一个值,例如。

     double y = s1.getMinY() + ((s1.getMaxY() - s1.getMinY()) / 2);
    
  3. 最后,我们构建注释并将其添加到图中。

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