2

I bumped into this problem when I created a chart that need a axis with week period.

When I set up tick unit of DateAxis with new DateTickUnit(DateTickUnitType.Day, 7), it display tick mark every 7 days. However, the date of tick mark does not start from the first day of the week. You can observer this behavior in the screenshot.

Cyan color line 05-01 w18(May. 1, Week 18) is below the w18(Week 18) tick mark, this is because the date of tick mark w18 are actually May 2, which is Wednesday.

This make chart looks incorrect because people tend to think each tick are suppose to be the start of the week.

After I check the source code, I found out that DateAxis dose not support such behavior for week (There is no week type anyway).

I cannot to create another DateTickUnitType because the private constructor, and correctTickDateForPosition() method in DateAxis is also private. I have tried to override the nextStandardDate() but did not come out with satisfy result.

How can I make DateAxis always draw tick mark start from first day of week ?


Here is the screenshot and example code

Chart with DateAxis in week period

JFreeChart/JCommon required

public class Main extends ApplicationFrame {

  public Main (String title) throws ParseException {
    super(title);
    JPanel chartPanel = createDemoPanel();
    chartPanel.setPreferredSize(new java.awt.Dimension(800, 600));
    setContentPane(chartPanel);
  }

  private static JFreeChart createChart(XYDataset dataset) {
    JFreeChart chart = ChartFactory.createXYLineChart("Week period in DateAxis", "X", "Y", 
        dataset, PlotOrientation.VERTICAL, true, true, false);

    DateAxis x = new DateAxis("X");
    x.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH, 1, new SimpleDateFormat("MMM.")));

    DateAxis y = new DateAxis("Y");
    y.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 7, new SimpleDateFormat("MM-dd 'W'w.")));

    XYPlot plot = chart.getXYPlot();
    plot.setDomainAxis(x);
    plot.setRangeAxis(y);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinesVisible(true);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator("{2}", 
        new SimpleDateFormat("MMM."), new SimpleDateFormat("MM-dd 'w'w")));
    renderer.setBaseItemLabelsVisible(true);
    return chart;
  }

  private static XYDataset createDataset() throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

    String[] allDate = new String[]{
        "2012/03/27", "2012/04/03", "2012/04/10", 
        "2012/04/17", "2012/04/24", "2012/05/01"};

    String dateY1 = "2012/01/15";
    String dateY2 = "2012/02/15";
    String dateY3 = "2012/03/15";
    String dateY4 = "2012/04/15";
    String dateY5 = "2012/05/15";
    String dateY6 = "2012/06/15";

    XYSeriesCollection dataset = new XYSeriesCollection();
    for (String date : allDate) {
      XYSeries series = new XYSeries(date);

      series.add(df.parse(dateY1).getTime(), df.parse(date).getTime());
      series.add(df.parse(dateY2).getTime(), df.parse(date).getTime());
      series.add(df.parse(dateY3).getTime(), df.parse(date).getTime());
      series.add(df.parse(dateY4).getTime(), df.parse(date).getTime());
      series.add(df.parse(dateY5).getTime(), df.parse(date).getTime());
      series.add(df.parse(dateY6).getTime(), df.parse(date).getTime());
      dataset.addSeries(series);
    }
    return dataset;
  }

  public static JPanel createDemoPanel() throws ParseException {
    JFreeChart chart = createChart(createDataset());
    return new ChartPanel(chart);
  }

  public static void main(String[] args) throws ParseException {
    Main demo = new Main("Test");
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
  }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Rangi Lin
  • 9,303
  • 6
  • 45
  • 71

2 Answers2

6

Here is the my version of the DateAxis that supported week period (only).

public static class WeeklyDateAxis extends DateAxis {

  private static final long serialVersionUID = 1L;
  private Locale locale;

  public WeeklyDateAxis(String label, TimeZone zone, Locale locale) {
    super(label, zone, locale);
    this.locale = locale;
  }

  @Override
  protected Date previousStandardDate(Date date, DateTickUnit unit) {
    Calendar cal = Calendar.getInstance(getTimeZone(), locale);
    cal.setTime(date);
    resetFieldBelowDay(cal);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    return cal.getTime();
  }

  @Override
  protected Date nextStandardDate(Date date, DateTickUnit unit) {
    Date previous = previousStandardDate(date, unit);
    Calendar cal = Calendar.getInstance(getTimeZone(), locale);
    cal.setTime(previous);
    resetFieldBelowDay(cal);

    cal.add(Calendar.WEEK_OF_YEAR, 1);
    return cal.getTime();
  }

  private void resetFieldBelowDay(Calendar cal) {
    cal.clear(Calendar.MILLISECOND);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MINUTE);
    cal.set(Calendar.HOUR_OF_DAY, 0);
  }
}

Explanation :

When DateAxis calculate ticks, it will start from the lowest value by calling

nextStandardDate(getMinimumDate(), unit);

, where getMinimumDate() are the edge value of the chart. Then it will keep using the last tick of date as input to calculate next date until it reach the highest available date.

So I set the time to first day of week in previousStandardDate(), then every time I calculate the next tick, I add one week to result of the previousStandardDate().

The resetFieldBelowDay() part are simply to remove some noise data that can cause line dose not align with the tick.

Here is another data set I use to validate the result, you can simply replace the it with the example code I provide in question.

private static XYDataset createDataset() throws ParseException {
  SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

  String[][] allDate = new String[][] {
      {"2012/03/25", "2012/03/29", "2012/03/28", "2012/03/27", "2012/03/27", "2012/03/27"},
      {"2012/04/01", "2012/04/02", "2012/04/06", "2012/04/06", "2012/04/06", "2012/04/06"},
      {"2012/04/11", "2012/04/12", "2012/04/08", "2012/04/10", "2012/04/10", "2012/04/10"},
      {"2012/04/15", "2012/04/14", "2012/04/15", "2012/04/18", "2012/04/19", "2012/04/19"},
      {"2012/05/01", "2012/05/02", "2012/05/08", "2012/05/04", "2012/05/04", "2012/05/04"},
      {"2012/05/12", "2012/05/12", "2012/05/18", "2012/05/14", "2012/05/14", "2012/05/14"},
      {"2012/05/22", "2012/05/22", "2012/05/28", "2012/05/28", "2012/05/28", "2012/05/30"},
  };

  String dateY1 = "2012/01/15";
  String dateY2 = "2012/02/15";
  String dateY3 = "2012/03/15";
  String dateY4 = "2012/04/15";
  String dateY5 = "2012/05/15";
  String dateY6 = "2012/06/15";

  XYSeriesCollection dataset = new XYSeriesCollection();
  for (String[] dateOfOneSeries : allDate) {
    XYSeries series = new XYSeries(dateOfOneSeries[0]);

    series.add(df.parse(dateY1).getTime(), df.parse(dateOfOneSeries[0]).getTime());
    series.add(df.parse(dateY2).getTime(), df.parse(dateOfOneSeries[1]).getTime());
    series.add(df.parse(dateY3).getTime(), df.parse(dateOfOneSeries[2]).getTime());
    series.add(df.parse(dateY4).getTime(), df.parse(dateOfOneSeries[3]).getTime());
    series.add(df.parse(dateY5).getTime(), df.parse(dateOfOneSeries[4]).getTime());
    series.add(df.parse(dateY6).getTime(), df.parse(dateOfOneSeries[5]).getTime());
    dataset.addSeries(series);
  }
  return dataset;
}

Result :

Result

Rangi Lin
  • 9,303
  • 6
  • 45
  • 71
1

By overriding previousStandardDate of DateAxis I managed to adjust the day of the week for the tick marks.

In your example the data is displayed for Tuesdays, so in the code below the first day of week for Calendar is set to Tuesday, which aligns the data lines with the tick marks.

DateAxis y = new DateAxis("Y") {
  @Override
  protected Date previousStandardDate(Date date, DateTickUnit unit) {
    Date prevDate = super.previousStandardDate(date, unit);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(prevDate);

    int showDayOfWeek = Calendar.TUESDAY;
    calendar.setFirstDayOfWeek(showDayOfWeek);
    if (showDayOfWeek != calendar.get(Calendar.DAY_OF_WEEK)) {
      calendar.set(Calendar.DAY_OF_WEEK, showDayOfWeek);
    }

    return calendar.getTime();
  }
};

[Edit:] I just realized that you don't actually want to align the tick marks, but show them at the actual first day of the week. The solution for that would be

DateAxis y = new DateAxis("Y") {    
  @Override
  protected Date previousStandardDate(Date date, DateTickUnit unit) {
    Date prevDate = super.previousStandardDate(date, unit);

    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
    calendar.setTime(prevDate);

    int firstDayOfWeek = calendar.getFirstDayOfWeek();
    if (firstDayOfWeek != calendar.get(Calendar.DAY_OF_WEEK)) {
      calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
    }

    return calendar.getTime();
  }
};
Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
  • Your answer is pretty much what I did at first, excepted I override `nextStandardDate()`. Unfortunately, this way only works with the data set I provide. If you tweak data a bit, you will find out sometimes tick mark will exceed the chart But your answer inspired me, and helped me fix my own version. – Rangi Lin Jun 15 '12 at 15:29
  • By the way, you don't have to `getFirstDayOfWeek()` then `setFirstDayOfWeek()` again. – Rangi Lin Jun 15 '12 at 15:59