List of usage examples for org.jfree.data.time TimeSeries TimeSeries
public TimeSeries(Comparable name, Class timePeriodClass)
From source file:org.n52.oxf.render.sos.TimeSeriesMapChartRenderer.java
/** * The resulting chart consists a TimeSeries for each FeatureOfInterest contained in the * observationCollection.//from w ww .ja v a 2 s . co m * * @param foiIdArray * the IDs of the FeaturesOfInterest whose Observations shall be rendered * @param observationCollection * @return */ protected XYPlot drawChart4FOI(String foiID, Map<ITimePosition, ObservedValueTuple> timeMap) { TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeries timeSeries = new TimeSeries(foiID, Second.class); for (ITimePosition timePos : timeMap.keySet()) { Number value = (Number) timeMap.get(timePos).getValue(0); timeSeries.add( new Second(new Float(timePos.getSecond()).intValue(), timePos.getMinute(), timePos.getHour(), timePos.getDay(), timePos.getMonth(), new Long(timePos.getYear()).intValue()), value); } dataset.addSeries(timeSeries); dataset.setDomainIsPointsInTime(true); // // create Plot: // XYPlot plot = new XYPlot(); plot.setDataset(dataset); plot.setBackgroundPaint(Color.white); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setBaseShapesVisible(false); plot.setRenderer(renderer); DateAxis dateAxis = new DateAxis(); dateAxis.setTickMarkPosition(DateTickMarkPosition.START); dateAxis.setTickMarksVisible(true); dateAxis.setVerticalTickLabels(true); dateAxis.setDateFormatOverride(new SimpleDateFormat("dd'.'MM'.'")); plot.setDomainAxis(dateAxis); plot.setRangeAxis(new NumberAxis()); return plot; }
From source file:de.fischer.thotti.reportgen.diagram.ChartGenerator.java
public ChartMetaData generateAllVariantsChart(final String testId) { File chartFile;/* w w w . j a v a2 s . c o m*/ try { final List<TestVariant> variants = persistenceHelper.findAllVariants(testId); final TimeSeriesCollection collection = new TimeSeriesCollection(); String svgFilename = String.format("%s.svg", testId); chartFile = new File(baseDir, svgFilename); for (TestVariant variant : variants) { TimeSeries series = new TimeSeries(String.format("Average of %s", variant.getCombinedId()), Day.class); TimeSeries mediaSeries = new TimeSeries("Median of " + variant, Day.class); List<NDResultEntity> results = persistenceHelper.findAllResultsForVariant(variant); SortedSet<NDResultEntity> sortedSet = new TreeSet<NDResultEntity>( new TestVariantModel.DateComparator()); sortedSet.addAll(results); Calendar now = Calendar.getInstance(); now.add(Calendar.DATE, 1); Iterator<Measurement> itr = new AverageDayCombinerIterator(sortedSet.iterator()); Iterator<DatePoint> medianItr = new MedianIterator(sortedSet.iterator()); while (itr.hasNext()) { Measurement singleResult = itr.next(); Date startDate = singleResult.getPointInTime(); double timeInMS = singleResult.getDuration(); double timeInSecs = convertMilliSecsToSeconds(timeInMS); series.add(new Day(startDate), timeInSecs); } while (medianItr.hasNext()) { DatePoint singleResult = medianItr.next(); Day day = new Day(singleResult.getPointInTime()); double value = convertMilliSecsToSeconds(singleResult.getValue()); mediaSeries.add(day, value); } collection.addSeries(series); collection.addSeries(mediaSeries); } final JFreeChart chart = createChart(testId, collection); saveChartAsSVG(chart, svgFilename); System.out.println(String.format("Written %s", chartFile.toString())); return new ChartMetaData().withFilename(chartFile.getName()).withWidth(DEFAULT_CHAR_WIDTH) .withHeight(DEFAULT_CHAR_HEIGHT).withFormat("SVG"); } catch (Exception ioe) { // @todo Throw an better exception! ioe.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; }
From source file:OverlaidXYPlotDemo2.java
/** * Creates a sample dataset./*from w w w . j av a2s. co m*/ * * @return The dataset. */ private XYDataset createDataset2A() { // create dataset 2... final TimeSeries series2 = new TimeSeries("Series 2", Day.class); series2.add(new Day(3, SerialDate.MARCH, 2002), 16853.2); series2.add(new Day(4, SerialDate.MARCH, 2002), 19642.3); series2.add(new Day(5, SerialDate.MARCH, 2002), 18253.5); series2.add(new Day(6, SerialDate.MARCH, 2002), 15352.3); series2.add(new Day(7, SerialDate.MARCH, 2002), 13532.0); series2.add(new Day(8, SerialDate.MARCH, 2002), 12635.3); series2.add(new Day(9, SerialDate.MARCH, 2002), 13998.2); series2.add(new Day(10, SerialDate.MARCH, 2002), 11943.2); series2.add(new Day(11, SerialDate.MARCH, 2002), 16943.9); series2.add(new Day(12, SerialDate.MARCH, 2002), 17843.2); series2.add(new Day(13, SerialDate.MARCH, 2002), 16495.3); series2.add(new Day(14, SerialDate.MARCH, 2002), 17943.6); series2.add(new Day(15, SerialDate.MARCH, 2002), 18500.7); series2.add(new Day(16, SerialDate.MARCH, 2002), 19595.9); final TimeSeriesCollection result = new TimeSeriesCollection(series2); result.setXPosition(TimePeriodAnchor.MIDDLE); return result; }
From source file:edu.unibonn.kmeans.mapreduce.plotting.TimeSeriesPlotter_KMeans.java
private XYDataset createDataset_centroids(ArrayList<Cluster_KMeans> clusters, LocalDateTime from) { final TimeSeriesCollection dataset = new TimeSeriesCollection(); for (int i = 0; i < clusters.size(); i++) { Cluster_KMeans current_cluster = clusters.get(i); double[] center_of_mass = current_cluster.getCenter_of_mass(); final TimeSeries s1 = new TimeSeries("Cluster_" + current_cluster.getCluster_id(), Hour.class); for (int j = 0; j < 24; j++) { s1.add(new Hour(j, from.getDayOfMonth(), from.getMonthValue(), from.getYear()), center_of_mass[j]); }/* ww w . ja v a2 s.c o m*/ dataset.addSeries(s1); } dataset.setDomainIsPointsInTime(true); return dataset; }
From source file:org.jfree.data.time.TimeSeriesTest.java
/** * Basic tests for the delete() method.//w w w . j ava2 s . com */ @Test public void testDelete2() { TimeSeries s1 = new TimeSeries("Series", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } }
From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java
public static TimeSeriesChart generateTimeSeriesChart(Properties ctx, String title, String subtitle, int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter) throws OperationException { TimeSeriesChart timeSeriesChart = new TimeSeriesChart(); timeSeriesChart.setTitle(title);//from w w w .ja v a2 s.c o m timeSeriesChart.setSubtitle(subtitle); timeSeriesChart.setShowShapes(true); //timeSeriesChart.getDataSetFromSQL(timeSeriesChartSQL); String timeSeriesChartSQL = SalesAnalysisReportManager.getTimeSeriesDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup); ArrayList<Object[]> list = ReportManager.getReportData(ctx, timeSeriesChartSQL, false); TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeries series = null; String yLabel = null; String seriesName = null; String date = null; BigDecimal price = null; String[] s = null; int day, month, year; for (Object[] data : list) { seriesName = (String) data[0]; date = (String) data[1]; price = (BigDecimal) data[2]; s = date.split("-"); if (s.length != 3) throw new OperationException("Unable to generate timeseries. " + "Cause:Invalid date format, the date returned should have the following format 'DD-MM-YYYY'"); SimpleDateFormat sdf = new SimpleDateFormat(); Calendar cal = Calendar.getInstance(); Date d = null; try { sdf.applyPattern("dd-MM-yyyy"); d = sdf.parse(date); } catch (ParseException e1) { try { sdf.applyPattern("dd-MMM-yyyy"); d = sdf.parse(date); } catch (ParseException e) { throw new OperationException("Unable to generate timeseries. " + "Cause:Invalid date format, the date returned should have one of the following formats 'DD-MM-YYYY' or 'DD-MMM-YYYY'", e); } } cal.setTime(d); day = cal.get(Calendar.DATE); month = cal.get(Calendar.MONTH) + 1; year = cal.get(Calendar.YEAR); series = dataset.getSeries(seriesName); if (series == null) { series = new TimeSeries(seriesName, Day.class); series.add(new Day(day, month, year), price); dataset.addSeries(series); } else { series.add(new Day(day, month, year), price); } //if } //for if (priceQtyFilter.equalsIgnoreCase(Constants.PRICE)) { //against price String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol(); yLabel = "Value (" + currency + ")"; } else { yLabel = "Quantity"; } timeSeriesChart.setYLabel(yLabel); timeSeriesChart.setDataset(dataset); XYPlot plot = (XYPlot) timeSeriesChart.getChart().getPlot(); DateAxis axis = (DateAxis) plot.getDomainAxis(); SimpleDateFormat sdf = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1); axis.setRange(fromDate, toDate); //axis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1,new SimpleDateFormat("MMM-yyyy"))); timeSeriesChart.getChart().setBackgroundPaint(Color.white); return timeSeriesChart; }
From source file:org.jfree.chart.demo.MarkerDemo1.java
/** * Returns a sample data series (for supplier 1). * * @return A sample data series./*from ww w . j a v a 2 s . co m*/ */ private TimeSeries createSupplier1Bids() { final Hour hour = new Hour(1, new Day(22, 5, 2003)); final TimeSeries series1 = new TimeSeries("Supplier 1", Minute.class); series1.add(new Minute(13, hour), 200.0); series1.add(new Minute(14, hour), 195.0); series1.add(new Minute(45, hour), 190.0); series1.add(new Minute(46, hour), 188.0); series1.add(new Minute(47, hour), 185.0); series1.add(new Minute(52, hour), 180.0); return series1; }
From source file:ca.myewb.frame.servlet.GraphServlet.java
private JFreeChart getDailyIntegratedStats(Session s) throws CloneNotSupportedException { JFreeChart chart;//from w w w. j a va2 s . c o m List<DailyStatsModel> stats = (new SafeHibList<DailyStatsModel>( s.createQuery("select ds from DailyStatsModel as ds where day<? and day>=? order by day desc") .setDate(0, new Date()).setDate(1, GraphServlet.getStartDate()))).list(); TimeSeriesCollection theData = new TimeSeriesCollection(); TimeSeriesCollection theData2 = new TimeSeriesCollection(); TimeSeries users = new TimeSeries("Total Users", Day.class); theData.addSeries(users); TimeSeries regulars = new TimeSeries("Regular Members", Day.class); theData2.addSeries(regulars); int numUsers = Helpers.getGroup("Org").getNumMembers(); int numReg = Helpers.getGroup("Regular").getNumMembers(); for (DailyStatsModel ds : stats) { Day theDay = new Day(ds.getDay()); users.add(theDay, numUsers); regulars.add(theDay, numReg); numUsers -= (ds.getMailinglistsignups() + ds.getSignups() - ds.getDeletions()); numReg -= (ds.getRegupgrades() - ds.getRegdowngrades()); } chart = ChartFactory.createTimeSeriesChart("Membership", "Day", "Users", theData, true, true, true); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis axis2 = new NumberAxis("Regular Members"); plot.setRangeAxis(1, axis2); plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT); plot.setDataset(1, MovingAverage.createMovingAverage(theData2, "", 14, 0)); plot.mapDatasetToRangeAxis(1, 1); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(0); renderer.setSeriesStroke(0, new BasicStroke(2.0f)); renderer = (XYLineAndShapeRenderer) renderer.clone(); renderer.setSeriesStroke(0, new BasicStroke(2.0f)); plot.setRenderer(1, renderer); return chart; }
From source file:com.jaxzin.iraf.forecast.swing.JForecaster.java
@SuppressWarnings({ "MethodWithMultipleLoops" }) protected XYDataset createDataset() { final TimeSeriesCollection tsc = new TimeSeriesCollection(); // long start = System.currentTimeMillis(); Forecast forecastData = null;// w ww. j a v a2 s. c om try { // System.out.println("Generating dataset; initial salary is <"+domain.getInitialSalary()+">"); forecastData = forecaster.forecast(domain); } catch (ForecastException e) { e.printStackTrace(); } int count = 1; assert forecastData != null; final int total = forecastData.getForecastData().size() + 1; //noinspection ForLoopThatDoesntUseLoopVariable for (Iterator i = forecastData.getForecastData().iterator(); i.hasNext(); count++) { final List<Money> universeData = (List<Money>) i.next(); //noinspection ObjectAllocationInLoop,UnqualifiedStaticUsage final TimeSeries ts = new TimeSeries(new StringBuilder() .append(String.valueOf((count * TOTAL_PERCENTILES) / total)).append("th").toString(), Year.class); for (Money money : universeData) { if (ts.getItemCount() == 0) { //noinspection ObjectAllocationInLoop ts.add(RegularTimePeriod.createInstance(Year.class, new Date(), TimeZone.getDefault()), money.doubleValue()); } else { ts.add(ts.getNextTimePeriod(), money.doubleValue()); } } tsc.addSeries(ts); } // System.out.println(System.currentTimeMillis()-start); return tsc; }
From source file:com.freedomotic.plugins.devices.harvester_chart.HarvesterChart.java
@ListenEventsOn(channel = "app.event.sensor.object.behavior.clicked") public void onObjectClicked(EventTemplate event) { List<String> behavior_list = new ArrayList<String>(); System.out.println("received event " + event.toString()); ObjectReceiveClick clickEvent = (ObjectReceiveClick) event; //PRINT EVENT CONTENT WITH System.out.println(clickEvent.getPayload().toString()); String objectName = clickEvent.getProperty("object.name"); String protocol = clickEvent.getProperty("object.protocol"); String address = clickEvent.getProperty("object.address"); try {/*from w ww. j av a2s .c om*/ Statement stat = connection.createStatement(); System.out.println("Protocol=" + protocol + ",Address=" + address); //for (EnvObjectLogic object : EnvObjectPersistence.getObjectByProtocol("wifi_id")){ //EnvObjectLogic object = EnvObjectPersistence.getObjectByName(objectName); for (EnvObjectLogic object : EnvObjectPersistence.getObjectByAddress(protocol, address)) { for (BehaviorLogic behavior : object.getBehaviors()) { System.out.println(behavior.getName()); } } //String query = "select date,value from events where protocol='"+clickEvent.getProperty("object.protocol")+"' and behavior='power' ORDER BY ID DESC LIMIT 1000;"; String query = "select date,value from events where object='" + objectName + "' and behavior='power' ORDER BY ID DESC LIMIT 1000;"; System.out.println(query); //String query = "select datetime(date, 'unixepoch', 'localtime') as TIME,value from events where protocol='remote_receiver' and behavior='button'"; ResultSet rs = stat.executeQuery(query); //JFreeChart chart = ChartFactory.createLineChart("Test", "Id", "Score", dataset, PlotOrientation.VERTICAL, true, true, false); //System.out.println("Wilson Kong Debug:"+rs.getLong("date")); final TimeSeries series = new TimeSeries("Data1", Millisecond.class); while (rs.next()) { Date resultdate = new Date(rs.getLong("date") * 1000); Millisecond ms_read = new Millisecond(resultdate); series.addOrUpdate(ms_read, rs.getDouble("value")); //series.add((Millisecond)rs.getLong("date"),(double)rs.getLong("value")); } XYDataset xyDataset = new TimeSeriesCollection(series); JFreeChart chart = ChartFactory.createTimeSeriesChart("Chart", "TIME", "VALVE", xyDataset, true, // legend true, // tooltips false // urls ); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(800, 500)); JFrame f = new JFrame("Chart"); f.setContentPane(chartPanel); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.pack(); f.setVisible(true); //if (...) { //MyFrame myFrame = new MyFrame(); //bindGuiToPlugin(myFrame); //showGui(); //triggers the showing of your frame. Before it calls onShowGui() //} } catch (SQLException ex) { Logger.getLogger(HarvesterChart.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage()); System.out.println("Wilson Kong Error: " + ex.toString()); //ex.printStackTrace(); stop(); } }