jtablesaw / tablesaw

Java dataframe and visualization library
https://jtablesaw.github.io/tablesaw/
Apache License 2.0
3.55k stars 643 forks source link

Grouping does not work on TimeSeriesPlot for DateTimeColumn #782

Open Sparkwired opened 4 years ago

Sparkwired commented 4 years ago

The following will not work when the timestamp column is a DateTimeColumn instead of a DateColumn:

Figure timeseries = TimeSeriesPlot.create("Ask price", t, "timestamp", "ask_price", "series");

java.lang.ClassCastException: tech.tablesaw.api.DateTimeColumn cannot be cast to tech.tablesaw.api.DateColumn at tech.tablesaw.table.Relation.dateColumn(Relation.java:444) at tech.tablesaw.plotly.api.TimeSeriesPlot.create(TimeSeriesPlot.java:27)

Sparkwired commented 4 years ago

This is a quick and dirty fix:

public static Figure create( String title, Table table, String dateColX, String yCol, String groupCol) {

        TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));

        Layout layout = Layout.builder(title, dateColX, yCol).build();

        ScatterTrace[] traces = new ScatterTrace[tables.size()];
        for (int i = 0; i < tables.size(); i++) {
          List<Table> tableList = tables.asTableList();
          Table t = tableList.get(i).sortOn(dateColX);

          if (ColumnType.LOCAL_DATE.equals(table.column(dateColX).type())) {
              traces[i] =
                      ScatterTrace.builder(t.dateColumn(dateColX), t.numberColumn(yCol))
                          .showLegend(true)
                          .name(tableList.get(i).name())
                          .mode(ScatterTrace.Mode.LINE)
                          .build();
          } else if (ColumnType.LOCAL_DATE_TIME.equals(table.column(dateColX).type())) {
              traces[i] =
                      ScatterTrace.builder(t.dateTimeColumn(dateColX), t.numberColumn(yCol))
                          .showLegend(true)
                          .name(tableList.get(i).name())
                          .mode(ScatterTrace.Mode.LINE)
                          .build();
          }

        }
        return new Figure(layout, traces);
      }