List of usage examples for org.jfree.chart.plot XYPlot setDataset
public void setDataset(int index, XYDataset dataset)
From source file:jboost.visualization.HistogramFrame.java
private JFreeChart createHistogramChart() { XYBarRenderer renderer1 = new XYBarRenderer(); renderer1.setSeriesPaint(0, Color.cyan); renderer1.setSeriesPaint(1, Color.pink); XYPlot histPlot = new XYPlot(histogramDataset, null, new NumberAxis("count"), renderer1); XYBarRenderer renderer2 = new XYBarRenderer(); renderer2.setSeriesPaint(0, Color.green); renderer2.setSeriesPaint(1, Color.orange); renderer2.setUseYInterval(true);//from www . java 2s . co m // weight and potential if (infoParser.isRobustBoost || infoParser.isAdaBoost || infoParser.isLogLossBoost) { StandardXYItemRenderer renderer3 = new StandardXYItemRenderer(); renderer3.setSeriesPaint(0, Color.blue); renderer3.setSeriesPaint(1, Color.red); renderer3.setBaseStroke(new BasicStroke(2)); StandardXYItemRenderer renderer4 = new StandardXYItemRenderer(); renderer4.setSeriesPaint(0, Color.blue); renderer4.setSeriesPaint(1, Color.red); renderer4.setBaseStroke( new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2, new float[] { 2 }, 0)); histPlot.setDataset(1, weightDataset); histPlot.setRenderer(1, renderer3); histPlot.setDataset(2, potentialDataset); histPlot.setRenderer(2, renderer4); histPlot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); } XYPlot fluctPlot = new XYPlot(fluctDataset, null, new NumberAxis("bin"), renderer2); double initialLocation = (upper_limit + lower_limit) / 2.0; histMarker = new IntervalMarker(initialLocation, initialLocation); histPlot.addDomainMarker(histMarker, Layer.BACKGROUND); fluctPlot.addDomainMarker(histMarker, Layer.BACKGROUND); // plot.setBackgroundPaint(Color.lightGray); // plot.setDomainGridlinePaint(Color.white); // plot.setRangeGridlinePaint(Color.white); CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(new NumberAxis("score")); combinedPlot.setGap(10.0); // add the subplots... ValueAxis axis = new NumberAxis(); axis.setRange(rawData.getMinRange(iter), rawData.getMaxRange(iter)); combinedPlot.add(histPlot, 3); combinedPlot.add(fluctPlot, 1); combinedPlot.setOrientation(PlotOrientation.VERTICAL); combinedPlot.setDomainAxis(axis); JFreeChart chart = new JFreeChart("Histogram", JFreeChart.DEFAULT_TITLE_FONT, combinedPlot, false // legend ); return chart; }
From source file:org.optaplanner.benchmark.impl.statistic.movecountperstep.MoveCountPerStepProblemStatistic.java
@Override public void writeGraphFiles(BenchmarkReport benchmarkReport) { Locale locale = benchmarkReport.getLocale(); NumberAxis xAxis = new NumberAxis("Time spent"); xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale)); NumberAxis yAxis = new NumberAxis("Accepted/selected moves per step"); yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale)); XYPlot plot = new XYPlot(null, xAxis, yAxis, null); DrawingSupplier drawingSupplier = new DefaultDrawingSupplier(); plot.setOrientation(PlotOrientation.VERTICAL); int seriesIndex = 0; for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { XYSeries acceptedSeries = new XYSeries( singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " accepted"); XYSeries selectedSeries = new XYSeries( singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " selected"); XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false); if (singleBenchmarkResult.isSuccess()) { MoveCountPerStepSingleStatistic singleStatistic = (MoveCountPerStepSingleStatistic) singleBenchmarkResult .getSingleStatistic(problemStatisticType); for (MoveCountPerStepStatisticPoint point : singleStatistic.getPointList()) { long timeMillisSpent = point.getTimeMillisSpent(); long acceptedMoveCount = point.getMoveCountPerStepMeasurement().getAcceptedMoveCount(); long selectedMoveCount = point.getMoveCountPerStepMeasurement().getSelectedMoveCount(); acceptedSeries.add(timeMillisSpent, acceptedMoveCount); selectedSeries.add(timeMillisSpent, selectedMoveCount); }/*from www .ja v a2s . c o m*/ } XYSeriesCollection seriesCollection = new XYSeriesCollection(); seriesCollection.addSeries(acceptedSeries); seriesCollection.addSeries(selectedSeries); plot.setDataset(seriesIndex, seriesCollection); if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { // Make the favorite more obvious renderer.setSeriesStroke(0, new BasicStroke(2.0f)); // Dashed line for selected move count renderer.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 2.0f, 6.0f }, 0.0f)); } else { // Dashed line for selected move count renderer.setSeriesStroke(1, new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 2.0f, 6.0f }, 0.0f)); } // Render both lines in the same color Paint linePaint = drawingSupplier.getNextPaint(); renderer.setSeriesPaint(0, linePaint); renderer.setSeriesPaint(1, linePaint); plot.setRenderer(seriesIndex, renderer); seriesIndex++; } JFreeChart chart = new JFreeChart(problemBenchmarkResult.getName() + " move count per step statistic", JFreeChart.DEFAULT_TITLE_FONT, plot, true); graphFile = writeChartToImageFile(chart, problemBenchmarkResult.getName() + "MoveCountPerStepStatistic"); }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.ApproximationSetPlot.java
@Override protected void update() { XYSeriesCollection dataset = new XYSeriesCollection(); for (ResultKey key : frame.getSelectedResults()) { NondominatedPopulation population = new EpsilonBoxDominanceArchive(EPSILON); for (Accumulator accumulator : controller.get(key)) { if (!accumulator.keySet().contains(metric)) { continue; }/*from w w w .j av a 2s. c om*/ List<?> list = (List<?>) accumulator.get(metric, accumulator.size(metric) - 1); for (Object object : list) { population.add((Solution) object); } } if (!population.isEmpty()) { XYSeries series = new XYSeries(key, false, true); for (Solution solution : population) { if (solution.getNumberOfObjectives() == 1) { series.add(solution.getObjective(0), solution.getObjective(0)); } else if (solution.getNumberOfObjectives() > 1) { series.add(solution.getObjective(0), solution.getObjective(1)); } } dataset.addSeries(series); } } JFreeChart chart = ChartFactory.createScatterPlot(metric, localization.getString("text.objective", 1), localization.getString("text.objective", 2), dataset, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true); for (int i = 0; i < dataset.getSeriesCount(); i++) { Paint paint = frame.getPaintHelper().get(dataset.getSeriesKey(i)); renderer.setSeriesStroke(i, new BasicStroke(3f, 1, 1)); renderer.setSeriesPaint(i, paint); renderer.setSeriesFillPaint(i, paint); } plot.setRenderer(renderer); //add overlay if (controller.getShowLastTrace() && (controller.getLastAccumulator() != null) && controller.getLastAccumulator().keySet().contains(metric)) { XYSeriesCollection dataset2 = new XYSeriesCollection(); NondominatedPopulation population = new EpsilonBoxDominanceArchive(EPSILON); if (controller.getLastAccumulator().keySet().contains(metric)) { List<?> list = (List<?>) controller.getLastAccumulator().get(metric, controller.getLastAccumulator().size(metric) - 1); for (Object object : list) { population.add((Solution) object); } } if (!population.isEmpty()) { XYSeries series = new XYSeries(localization.getString("text.last"), false, true); for (Solution solution : population) { series.add(solution.getObjective(0), solution.getObjective(1)); } dataset2.addSeries(series); } XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(false, true); renderer2.setSeriesPaint(0, Color.BLACK); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); } removeAll(); add(new ChartPanel(chart), BorderLayout.CENTER); revalidate(); repaint(); }
From source file:org.jfree.chart.demo.JFreeChartDemoBase.java
/** * Creates a combined and overlaid chart. * <p>/* ww w. j a v a 2 s .c o m*/ * Note: from version 0.9.10, the overlaid chart is no longer supported (you can achieve * the same result using a regular XYPlot with multiple datasets and renderers). * * @return a combined and overlaid chart. */ public JFreeChart createCombinedAndOverlaidChart1() { // create a default chart based on some sample data... final String title = this.resources.getString("combined.combined-overlaid.title"); final String subtitleStr = this.resources.getString("combined.combined-overlaid.subtitle"); final String domain = this.resources.getString("combined.combined-overlaid.domain"); final String[] ranges = this.resources.getStringArray("combined.combined-overlaid.ranges"); final TimeSeries jpy = DemoDatasetFactory.createJPYTimeSeries(); final TimeSeries mav = MovingAverage.createMovingAverage(jpy, "30 Day Moving Average", 30, 30); final TimeSeriesCollection dataset0 = new TimeSeriesCollection(); dataset0.addSeries(jpy); final TimeSeriesCollection dataset1 = new TimeSeriesCollection(); dataset1.addSeries(jpy); dataset1.addSeries(mav); final DefaultHighLowDataset highLowDataset = DemoDatasetFactory.createHighLowDataset(); final XYDataset highLowDatasetMA = MovingAverage.createMovingAverage(highLowDataset, " (MA)", 5 * 24 * 60 * 60 * 1000L, 5 * 24 * 60 * 60 * 1000L); // make one vertical axis for each (vertical) chart final NumberAxis[] valueAxis = new NumberAxis[3]; for (int i = 0; i < valueAxis.length; i++) { valueAxis[i] = new NumberAxis(ranges[i]); if (i <= 1) { valueAxis[i].setAutoRangeIncludesZero(false); // override default } } // create CombinedPlot... final CombinedDomainXYPlot parent = new CombinedDomainXYPlot(new DateAxis(domain)); final int[] weight = { 1, 2, 2 }; // add subplot1... final XYItemRenderer renderer1 = new StandardXYItemRenderer(); final XYPlot subplot1 = new XYPlot(dataset0, null, new NumberAxis(ranges[0]), renderer1); final NumberAxis axis1 = (NumberAxis) subplot1.getRangeAxis(); axis1.setTickLabelFont(new Font("Monospaced", Font.PLAIN, 7)); axis1.setLabelFont(new Font("SansSerif", Font.PLAIN, 8)); axis1.setAutoRangeIncludesZero(false); parent.add(subplot1, weight[0]); // add subplot2 (an overlaid plot)... final XYPlot subplot2 = new XYPlot(dataset0, null, new NumberAxis(ranges[1]), new StandardXYItemRenderer()); final NumberAxis axis2 = (NumberAxis) subplot2.getRangeAxis(); axis2.setTickLabelFont(new Font("Monospaced", Font.PLAIN, 7)); axis2.setLabelFont(new Font("SansSerif", Font.PLAIN, 8)); axis2.setAutoRangeIncludesZero(false); subplot2.setDataset(1, dataset1); subplot2.setRenderer(1, new StandardXYItemRenderer()); parent.add(subplot2, weight[1]); // add subplot3 (an overlaid plot)... final XYItemRenderer renderer3 = new HighLowRenderer(); final XYPlot subplot3 = new XYPlot(highLowDataset, null, new NumberAxis(ranges[2]), renderer3); final NumberAxis axis3 = (NumberAxis) subplot3.getRangeAxis(); axis3.setTickLabelFont(new Font("Monospaced", Font.PLAIN, 7)); axis3.setLabelFont(new Font("SansSerif", Font.PLAIN, 8)); axis3.setAutoRangeIncludesZero(false); subplot3.setDataset(1, highLowDatasetMA); subplot3.setRenderer(1, new StandardXYItemRenderer()); parent.add(subplot3, weight[2]); // now create the master JFreeChart object final JFreeChart chart = new JFreeChart(title, new Font("SansSerif", Font.BOLD, 12), parent, true); // then customise it a little... final TextTitle subtitle = new TextTitle(subtitleStr, new Font("SansSerif", Font.BOLD, 10)); chart.addSubtitle(subtitle); chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.blue)); return chart; }
From source file:fmiquerytest.Coordinates.java
static String drawTempRainChart(List<stepWeather> stepDataBase, Map routeWeather) { //First, fetch the real data List<Double> times = new ArrayList<>(); List<Double> temps = new ArrayList<>(); List<Double> rains = new ArrayList<>(); List<Double> lights = new ArrayList<>(); for (int i = 0; i < stepDataBase.size(); ++i) { stepWeather step = stepDataBase.get(i); stepWeather nextstep = step;/*from w w w . ja v a2s .co m*/ if (i < stepDataBase.size() - 1) { nextstep = stepDataBase.get(i + 1); } times.add(step.timeAsDouble); temps.add(getParameterAverage(routeWeather, step, nextstep, "Temperature")); rains.add(getParameterAverage(routeWeather, step, nextstep, "Precipitation1h")); lights.add(Math.pow(Math.abs(step.timeAsDouble % 24 - ((step.sunRise + step.sunSet) / 2)) / ((step.sunSet - step.sunRise) / 2), 5)); } double zeroPoint = times.get(0); // Make first dataset final TimeSeriesCollection dataset = new TimeSeriesCollection(); final TimeSeries s1 = new TimeSeries("Temperature C", Minute.class); // Make second dataset final TimeSeriesCollection dataset2 = new TimeSeriesCollection(); final TimeSeries s2 = new TimeSeries("Rain (mm)", Minute.class); // Make third dataset //final TimeSeriesCollection dataset3 = new TimeSeriesCollection(); final TimeSeries s3 = new TimeSeries("Darkness", Minute.class); // Show data per minute RegularTimePeriod start = new Minute(new Date(FmiQueryTest.startTimeMillis)); for (int i = 0; i < times.size() - 1; ++i) { double time = times.get(i); double nexttime = times.get(i + 1); int firstMinute = intValue((time - zeroPoint) * 60); int currentMinute = firstMinute; int lastMinute = intValue((nexttime - zeroPoint) * 60); while (currentMinute < lastMinute) { s1.add(start, temps.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute) * (temps.get(i + 1) - temps.get(i))); s2.add(start, (rains.get(i) + rains.get(i + 1)) / 2); //+((double)currentMinute-firstMinute)/(lastMinute-firstMinute)*(rains.get(i+1)-rains.get(i))); s3.add(start, lights.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute) * (lights.get(i + 1) - lights.get(i))); ++currentMinute; start = start.next(); } } dataset.addSeries(s1); dataset2.addSeries(s3); dataset2.addSeries(s2); // Initialize chart final JFreeChart chart = ChartFactory.createTimeSeriesChart("Temperature and rain", "Time", "Temperature C", dataset, true, // legend? true, // tooltips? false // URLs? ); final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLowerMargin(0.0); plot.getDomainAxis().setUpperMargin(0.0); // configure the range axis to display first dataset... final ValueAxis rangeAxis = (ValueAxis) plot.getRangeAxis(); rangeAxis.setRange(-30, 30); final TickUnits units = new TickUnits(); units.add(new NumberTickUnit(10.0)); units.add(new NumberTickUnit(1.0)); units.add(new NumberTickUnit(0.1)); rangeAxis.setStandardTickUnits(units); //rangeAxis.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16)); // add the secondary dataset/renderer/axis plot.setRangeAxis(rangeAxis); final XYItemRenderer renderer2 = new XYAreaRenderer(); final ValueAxis axis2 = new NumberAxis("Rain (mm) "); axis2.setRange(0, 2); axis2.setStandardTickUnits(units); //axis2.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16)); renderer2.setSeriesPaint(0, new Color(0, 0, 255, 128)); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); final XYItemRenderer renderer3 = new XYAreaRenderer(); renderer3.setSeriesPaint(0, new Color(0, 0, 0, 64)); //plot.setDataset(1, dataset2); plot.setRenderer(1, renderer3); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); chart.setBackgroundPaint(Color.white); //plot.setBackgroundPaint(Color.lightGray); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.black); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.black); // final TextTitle subtitle = new TextTitle("An area chart demonstration. We use this " // + "subtitle as an example of what happens when you get a really long title or " // + "subtitle."); // subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12)); // subtitle.setPosition(RectangleEdge.TOP); //// subtitle.setSpacer(new Spacer(Spacer.RELATIVE, 0.05, 0.05, 0.05, 0.05)); // subtitle.setVerticalAlignment(VerticalAlignment.BOTTOM); // chart.addSubtitle(subtitle); // Produce chart // ChartFrame frame = new ChartFrame("Tamperature and rain", chart); // frame.pack(); // RefineryUtilities.centerFrameOnScreen(frame); // frame.setVisible(true); ByteArrayOutputStream bas = new ByteArrayOutputStream(); try { ChartUtilities.writeChartAsPNG(bas, chart, 600, 400); } catch (IOException ex) { Logger.getLogger(WeatherTools.class.getName()).log(Level.SEVERE, null, ex); } byte[] byteArray = bas.toByteArray(); String baseCode = Base64.encode(byteArray); return "<img width=\"480\" alt=\"Temperature and rain\" src=\"data:image/png;base64," + baseCode.trim() + "\" />"; }
From source file:dk.netarkivet.harvester.harvesting.monitor.StartedJobHistoryChartGen.java
/** * Generates a chart in PNG format./*from w w w.j av a2 s .c o m*/ * * @param outputFile the output file, it should exist. * @param pxWidth the image width in pixels. * @param pxHeight the image height in pixels. * @param chartTitle the chart title, may be null. * @param xAxisTitle the x axis title * @param yDataSeriesRange the axis range (null for auto) * @param yDataSeriesTitles the Y axis titles. * @param timeValuesInSeconds the time values in seconds * @param yDataSeries the Y axis value series. * @param yDataSeriesColors the Y axis value series drawing colors. * @param yDataSeriesTickSuffix TODO explain argument yDataSeriesTickSuffix * @param drawBorder draw, or not, the border. * @param backgroundColor the chart background color. */ final void generatePngChart(File outputFile, int pxWidth, int pxHeight, String chartTitle, String xAxisTitle, String[] yDataSeriesTitles, double[] timeValuesInSeconds, double[][] yDataSeriesRange, double[][] yDataSeries, Color[] yDataSeriesColors, String[] yDataSeriesTickSuffix, boolean drawBorder, Color backgroundColor) { // Domain axis NumberAxis xAxis = new NumberAxis(xAxisTitle); xAxis.setFixedDimension(CHART_AXIS_DIMENSION); xAxis.setLabelPaint(Color.black); xAxis.setTickLabelPaint(Color.black); double maxSeconds = getMaxValue(timeValuesInSeconds); TimeAxisResolution xAxisRes = TimeAxisResolution.findTimeUnit(maxSeconds); xAxis.setTickUnit(new NumberTickUnit(xAxisRes.tickStep)); double[] scaledTimeValues = xAxisRes.scale(timeValuesInSeconds); String tickSymbol = I18N.getString(locale, "running.job.details.chart.timeunit.symbol." + xAxisRes.name()); xAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + tickSymbol + "'")); // First dataset String firstDataSetTitle = yDataSeriesTitles[0]; XYDataset firstDataSet = createXYDataSet(firstDataSetTitle, scaledTimeValues, yDataSeries[0]); Color firstDataSetColor = yDataSeriesColors[0]; // First range axis NumberAxis firstYAxis = new NumberAxis(firstDataSetTitle); firstYAxis.setFixedDimension(CHART_AXIS_DIMENSION); setAxisRange(firstYAxis, yDataSeriesRange[0]); firstYAxis.setLabelPaint(firstDataSetColor); firstYAxis.setTickLabelPaint(firstDataSetColor); String firstAxisTickSuffix = yDataSeriesTickSuffix[0]; if (firstAxisTickSuffix != null && !firstAxisTickSuffix.isEmpty()) { firstYAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + firstAxisTickSuffix + "'")); } // Create the plot with domain axis and first range axis XYPlot plot = new XYPlot(firstDataSet, xAxis, firstYAxis, null); XYLineAndShapeRenderer firstRenderer = new XYLineAndShapeRenderer(true, false); plot.setRenderer(firstRenderer); plot.setOrientation(PlotOrientation.VERTICAL); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); firstRenderer.setSeriesPaint(0, firstDataSetColor); // Now iterate on next axes for (int i = 1; i < yDataSeries.length; i++) { // Create axis String seriesTitle = yDataSeriesTitles[i]; Color seriesColor = yDataSeriesColors[i]; NumberAxis yAxis = new NumberAxis(seriesTitle); yAxis.setFixedDimension(CHART_AXIS_DIMENSION); setAxisRange(yAxis, yDataSeriesRange[i]); yAxis.setLabelPaint(seriesColor); yAxis.setTickLabelPaint(seriesColor); String yAxisTickSuffix = yDataSeriesTickSuffix[i]; if (yAxisTickSuffix != null && !yAxisTickSuffix.isEmpty()) { yAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + yAxisTickSuffix + "'")); } // Create dataset and add axis to plot plot.setRangeAxis(i, yAxis); plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT); plot.setDataset(i, createXYDataSet(seriesTitle, scaledTimeValues, yDataSeries[i])); plot.mapDatasetToRangeAxis(i, i); XYItemRenderer renderer = new StandardXYItemRenderer(); renderer.setSeriesPaint(0, seriesColor); plot.setRenderer(i, renderer); } // Create the chart JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, false); // Customize rendering chart.setBackgroundPaint(Color.white); chart.setBorderVisible(true); chart.setBorderPaint(Color.BLACK); // Render image try { ChartUtilities.saveChartAsPNG(outputFile, chart, pxWidth, pxHeight); } catch (IOException e) { LOG.error("Chart export failed", e); } }
From source file:com.charts.FiveDayChart.java
public FiveDayChart(YStockQuote currentStock) { TimeSeries series = new TimeSeries(currentStock.get_name()); ArrayList<String> fiveDayData = currentStock.get_five_day_data(); int length = fiveDayData.size(); for (int i = 22; i < length; i += 5) { String[] data = fiveDayData.get(i).split(","); Date time = new Date((long) Integer.parseInt(data[0]) * 1000); DateFormat df = new SimpleDateFormat("MM-dd-yyyy-h-m"); series.addOrUpdate(new Minute(time), Double.parseDouble(data[1])); }/*from ww w.j a va 2 s . c o m*/ String[] data = fiveDayData.get(length - 1).split(","); Date time = new Date((long) Integer.parseInt(data[0]) * 1000); DateFormat df = new SimpleDateFormat("MM-dd-yyyy-h-m"); series.addOrUpdate(new Minute(time), Double.parseDouble(data[1])); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart( currentStock.get_name() + "(" + currentStock.get_symbol() + ")" + " Five Day", "Date", "Price", dataset, true, true, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); ValueAxis yAxis = (ValueAxis) plot.getRangeAxis(); DateAxis xAxis = (DateAxis) plot.getDomainAxis(); Date now = new Date(); SegmentedTimeline segmentedTimeline = SegmentedTimeline.newFifteenMinuteTimeline(); segmentedTimeline.addBaseTimelineExclusions(segmentedTimeline.getStartTime(), now.getTime()); Calendar[][] holidays = DayRange.getHolidayDates(); for (int i = 0; i < holidays[0].length; i++) { Calendar day = Calendar.getInstance(); day.set(Calendar.YEAR, holidays[0][i].get(Calendar.YEAR)); day.set(Calendar.MONTH, holidays[0][i].get(Calendar.MONTH)); day.set(Calendar.DAY_OF_MONTH, holidays[0][i].get(Calendar.DAY_OF_MONTH)); day.set(Calendar.HOUR_OF_DAY, 9); segmentedTimeline.addException(day.getTimeInMillis(), day.getTimeInMillis() + 21600000); } xAxis.setTimeline(segmentedTimeline); xAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); //xAxis.setVerticalTickLabels(true); xAxis.setDateFormatOverride(new SimpleDateFormat("MM-dd")); xAxis.setAutoTickUnitSelection(false); xAxis.setAutoRange(false); StandardXYItemRenderer renderer1 = new StandardXYItemRenderer(); renderer1.setSeriesPaint(0, Color.BLUE); TimeSeries movingAverage5 = MovingAverage.createMovingAverage(series, "MA(5)", 30, 0); Double currMA5 = (Double) movingAverage5.getDataItem(movingAverage5.getItemCount() - 1).getValue(); currMA5 = Math.round(currMA5 * 100.0) / 100.0; movingAverage5.setKey("MA(5): " + currMA5); TimeSeriesCollection collection = new TimeSeriesCollection(); collection.addSeries(movingAverage5); plot.setDataset(1, collection); plot.setRenderer(1, renderer1); plot.setBackgroundPaint(Color.WHITE); chartPanel = new ChartPanel(chart); chart.setBackgroundPaint(chartPanel.getBackground()); plot.setDomainGridlinePaint(Color.lightGray); plot.setRangeGridlinePaint(Color.lightGray); chartPanel.setVisible(true); chartPanel.revalidate(); chartPanel.repaint(); }
From source file:edu.unibonn.kmeans.mapreduce.plotting.TimeSeriesPlotter_KMeans.java
/** * Creates a chart./*from w ww .j a v a2 s.c om*/ * * @param dataset a dataset. * @param clusters * * @return A chart. */ // private JFreeChart createChart(final XYDataset dataset, ArrayList<Cluster_DBScan> clusters) { // // final JFreeChart chart = ChartFactory.createTimeSeriesChart( // "Sensors", // "Time", "Erlang", // dataset, // false, //t // true, //t // false //f // ); // // ChartUtilities.applyCurrentTheme(chart); // // //chart.setBackgroundPaint(Color.white); // //// final StandardLegend sl = (StandardLegend) chart.getLegend(); //// sl.setDisplaySeriesShapes(true); // // final XYPlot plot = chart.getXYPlot(); // plot.setBackgroundPaint(Color.WHITE); // plot.setDomainGridlinePaint(Color.white); // plot.setRangeGridlinePaint(Color.white); //// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0)); // plot.setDomainCrosshairVisible(true); // plot.setRangeCrosshairVisible(true); // // final XYItemRenderer renderer = plot.getRenderer(); // // if (renderer instanceof StandardXYItemRenderer) // { // final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer; // //rr.setPlotShapes(true); // rr.setShapesFilled(true); // rr.setItemLabelsVisible(true); // } // // int temp_count = 0; // // //for (int i = 0; i < clusters.size(); i++) // for (int i = 0; (i < 11) && (i < clusters.size()); i++) // { // Cluster_DBScan current_cluster = clusters.get(i); // ArrayList<Day_24d> member_time_series = current_cluster.getMembership(); // // for (int j = 0; j < member_time_series.size(); j++) // { // renderer.setSeriesPaint(j+temp_count, getColor(i)); // } // temp_count = temp_count + member_time_series.size(); // } // // final DateAxis axis = (DateAxis) plot.getDomainAxis(); // axis.setDateFormatOverride(new SimpleDateFormat("HH:mm")); // // final ValueAxis axis_y = plot.getRangeAxis(); // axis_y.setRange(0, 100); // // return chart; // // } private JFreeChart createChart(final XYDataset dataset, final XYDataset dataset_centroids, ArrayList<Cluster_KMeans> clusters) { final JFreeChart chart = ChartFactory.createTimeSeriesChart("Sensors", "Time", "Erlang", dataset, false, //t true, //t false //f ); ChartUtilities.applyCurrentTheme(chart); //chart.setBackgroundPaint(Color.white); // final StandardLegend sl = (StandardLegend) chart.getLegend(); // sl.setDisplaySeriesShapes(true); final XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); final XYItemRenderer renderer = plot.getRenderer(); if (renderer instanceof StandardXYItemRenderer) { final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer; //rr.setPlotShapes(true); rr.setShapesFilled(true); rr.setItemLabelsVisible(true); } int temp_count = 0; //for (int i = 0; i < clusters.size(); i++) for (int i = 0; (i < 11) && (i < clusters.size()); i++) { Cluster_KMeans current_cluster = clusters.get(i); ArrayList<Day_24d> member_time_series = current_cluster.getMembership(); for (int j = 0; j < member_time_series.size(); j++) { renderer.setSeriesPaint(j + temp_count, getColor(i)); } temp_count = temp_count + member_time_series.size(); } final DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm")); //final ValueAxis axis_y = plot.getRangeAxis(); //axis_y.setRange(0, 20); plot.setDataset(1, dataset_centroids); plot.setRenderer(1, new StandardXYItemRenderer()); for (int i = 0; (i < clusters.size()); i++) { //plot.getRenderer(1).setSeriesPaint(i, getColor(i)); plot.getRenderer(1).setSeriesPaint(i, Color.BLACK); plot.getRenderer(1).setSeriesStroke(i, new BasicStroke(3.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 10.0f, 6.0f }, 0.0f)); } plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); return chart; }
From source file:net.sf.jasperreports.engine.fill.JRFillChart.java
/** * Build and configure a multiple axis chart. A multiple axis chart support more than * one range axis. Multiple datasets using different ranges can be displayed as long as * they share a common domain axis. Each dataset can be rendered differently, so one chart * can contain (for example) two line charts, a bar chart and an area chart. * <br><br>// ww w. ja v a2s . c o m * Multiple axis charts are handled differently than the other chart types. They do not * have a dataset, as each chart that is added to the multiple axis chart has its own * dataset. For simplicity, each dataset is treated as its own chart, and in fact we * reuse the design of all the chart types and let JFreeChart actually run them. Then * we pull out the bits we need and add it to the common chart. All the plot and chart * options on the nested charts is ignored, and all formatting is controlled by the plot * attached to the multiAxisChart. The one exception is seriesColor, which can be used in * a nested report to specify a color for a specific series in that report. * * @param evaluation current expression evaluation phase * @throws JRException */ protected void createMultiAxisChart(byte evaluation) throws JRException { // A multi axis chart has to have at least one axis and chart specified. // Create the first axis as the base plot, and then go ahead and create the // charts for any additional axes. Just take the renderer and data series // from those charts and add them to the first one. Plot mainPlot = null; JRFillMultiAxisPlot jrPlot = (JRFillMultiAxisPlot) getPlot(); // create a multi axis hyperlink provider MultiAxisChartHyperlinkProvider multiHyperlinkProvider = new MultiAxisChartHyperlinkProvider(); // Generate the main plot from the first axes specified. Iterator<JRChartAxis> iter = jrPlot.getAxes().iterator(); if (iter.hasNext()) { JRFillChartAxis axis = (JRFillChartAxis) iter.next(); JRFillChart fillChart = axis.getFillChart(); //a JFreeChart object should be obtained first; the rendering type should be always "vector" jfreeChart = fillChart.evaluateChart(evaluation); //FIXME honor printWhenExpression // Override the plot from the first axis with the plot for the multi-axis // chart. //FIXME is the above comment true? //configureChart(jfreeChart, getPlot(), evaluation); mainPlot = jfreeChart.getPlot(); ChartHyperlinkProvider axisHyperlinkProvider = fillChart.getHyperlinkProvider(); if (mainPlot instanceof CategoryPlot) { CategoryPlot categoryPlot = (CategoryPlot) mainPlot; categoryPlot.setRangeAxisLocation(0, getChartAxisLocation(axis)); if (axisHyperlinkProvider != null) { multiHyperlinkProvider.addHyperlinkProvider(categoryPlot.getDataset(), axisHyperlinkProvider); } } else if (mainPlot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) mainPlot; xyPlot.setRangeAxisLocation(0, getChartAxisLocation(axis)); if (axisHyperlinkProvider != null) { multiHyperlinkProvider.addHyperlinkProvider(xyPlot.getDataset(), axisHyperlinkProvider); } } } // Now handle all the extra axes, if any. int axisNumber = 0; while (iter.hasNext()) { JRFillChartAxis chartAxis = (JRFillChartAxis) iter.next(); JRFillChart fillChart = chartAxis.getFillChart(); fillChart.evaluatePrintWhenExpression(evaluation); if (!(fillChart.isPrintWhenExpressionNull() || fillChart.isPrintWhenTrue())) { continue; } axisNumber++; JFreeChart axisChart = fillChart.evaluateChart(evaluation); ChartHyperlinkProvider axisHyperlinkProvider = fillChart.getHyperlinkProvider(); // In JFreeChart to add a second chart type to an existing chart // you need to add an axis, a data series and a renderer. To // leverage existing code we simply create a new chart for the // axis and then pull out the bits we need and add them to the multi // chart. Currently JFree only supports category plots and xy plots // in a multi-axis chart, and you can not mix the two. if (mainPlot instanceof CategoryPlot) { CategoryPlot mainCatPlot = (CategoryPlot) mainPlot; if (!(axisChart.getPlot() instanceof CategoryPlot)) { throw new JRException(EXCEPTION_MESSAGE_KEY_MULTIAXIS_PLOT_TYPES_MIX_NOT_ALLOWED, (Object[]) null); } // Get the axis and add it to the multi axis chart plot CategoryPlot axisPlot = (CategoryPlot) axisChart.getPlot(); mainCatPlot.setRangeAxis(axisNumber, axisPlot.getRangeAxis()); mainCatPlot.setRangeAxisLocation(axisNumber, getChartAxisLocation(chartAxis)); // Add the data set and map it to the recently added axis mainCatPlot.setDataset(axisNumber, axisPlot.getDataset()); mainCatPlot.mapDatasetToRangeAxis(axisNumber, axisNumber); // Set the renderer to use to draw the dataset. mainCatPlot.setRenderer(axisNumber, axisPlot.getRenderer()); // Handle any color series for this chart configureAxisSeriesColors(axisPlot.getRenderer(), fillChart.getPlot()); if (axisHyperlinkProvider != null) { multiHyperlinkProvider.addHyperlinkProvider(axisPlot.getDataset(), axisHyperlinkProvider); } } else if (mainPlot instanceof XYPlot) { XYPlot mainXyPlot = (XYPlot) mainPlot; if (!(axisChart.getPlot() instanceof XYPlot)) { throw new JRException(EXCEPTION_MESSAGE_KEY_MULTIAXIS_PLOT_TYPES_MIX_NOT_ALLOWED, (Object[]) null); } // Get the axis and add it to the multi axis chart plot XYPlot axisPlot = (XYPlot) axisChart.getPlot(); mainXyPlot.setRangeAxis(axisNumber, axisPlot.getRangeAxis()); mainXyPlot.setRangeAxisLocation(axisNumber, getChartAxisLocation(chartAxis)); // Add the data set and map it to the recently added axis mainXyPlot.setDataset(axisNumber, axisPlot.getDataset()); mainXyPlot.mapDatasetToRangeAxis(axisNumber, axisNumber); // Set the renderer to use to draw the dataset. mainXyPlot.setRenderer(axisNumber, axisPlot.getRenderer()); // Handle any color series for this chart configureAxisSeriesColors(axisPlot.getRenderer(), fillChart.getPlot()); if (axisHyperlinkProvider != null) { multiHyperlinkProvider.addHyperlinkProvider(axisPlot.getDataset(), axisHyperlinkProvider); } } else { throw new JRException(EXCEPTION_MESSAGE_KEY_MULTIAXIS_PLOT_NOT_SUPPORTED, (Object[]) null); } } //set the multi hyperlink provider chartHyperlinkProvider = multiHyperlinkProvider; }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.SparkLine.java
private void addMarker(int index, double value, final Color color, float stoke, XYPlot plot) { logger.debug("IN"); TimeSeries markerSeries = new TimeSeries("Marker" + index, Month.class); for (Iterator iterator = yearsDefined.iterator(); iterator.hasNext();) { String currentYear = (String) iterator.next(); boolean stop = false; for (int i = 1; i < 13 && stop == false; i++) { if (!(currentYear.equalsIgnoreCase(yearsDefined.first()) && i < firstMonth.getMonth())) { markerSeries.add(new Month(i, Integer.valueOf(currentYear).intValue()), value); }//from w ww . j a v a 2 s . c o m if (currentYear.equalsIgnoreCase(lastYear) && i >= lastMonth.getMonth()) { stop = true; } } } final TimeSeriesCollection dataset = new TimeSeriesCollection(markerSeries); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) { public boolean getItemShapeVisible(int _series, int item) { return (false); } public Paint getItemPaint(int row, int column) { return color; } }; renderer.setBaseStroke(new BasicStroke(stoke, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); renderer.setDrawOutlines(true); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(Color.GRAY); renderer.setBaseOutlinePaint(Color.BLACK); renderer.setUseOutlinePaint(true); plot.setDataset(index, dataset); plot.setRenderer(index, renderer); logger.debug("OUT"); }