List of usage examples for org.jfree.chart ChartFactory createLineChart
public static JFreeChart createLineChart(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)
From source file:sms.Reports.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try {/*from w w w. j a v a2 s.c o m*/ methods m = new methods(); String query = "SELECT updated_at ,(maths+eng+chem+phy+geo+hist+bio+agri+bs+kiswa+cre)/11 FROM exam WHERE year='" + 1 + "'"; JDBCCategoryDataset dataset = new JDBCCategoryDataset(m.getConnection(), query); JFreeChart chart = ChartFactory.createBarChart("QUR", "year", "maths", dataset, PlotOrientation.VERTICAL, false, true, true); JFreeChart charti = ChartFactory.createLineChart("QUR", "year", "maths", dataset, PlotOrientation.VERTICAL, false, true, true); BarRenderer renderer = null; CategoryPlot plot = null; renderer = new BarRenderer(); ChartFrame frame = new ChartFrame("Chart", chart); frame.setVisible(true); frame.setSize(400, 450); ChartFrame frame1 = new ChartFrame("Chart", charti); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(dim.width / 10 - frame.getSize().width / 10, dim.height / 12 - frame.getSize().height / 12); frame1.setVisible(true); frame1.setSize(400, 450); frame1.setLocation(dim.width - frame1.getSize().width, dim.height - frame1.getSize().height); //.createAreaChart("QUERY CHART","maths"," eng", dataset,) } catch (SQLException ex) { Logger.getLogger(Reports.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:sipl.recursos.Graficar.java
public void DanhosY(int[][] values, int n, String direccion, String tiempo, String titulo) { try {//from w w w .ja va 2 s . co m DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (int j = 0; j < n; j++) { dataset.addValue(values[j][1], "Cantidad de Daos", "" + values[j][0]); } JFreeChart chart = ChartFactory.createLineChart(titulo, tiempo, "Cantidad", dataset, PlotOrientation.VERTICAL, true, true, true); try { ChartUtilities.saveChartAsJPEG(new File(direccion), chart, 500, 500); } catch (IOException e) { System.out.println("Error al abrir el archivo"); } } catch (Exception e) { System.out.println(e); } }
From source file:examples.MinimizingMakeChangeWithChart.java
/** * Executes the genetic algorithm to determine the minimum number of * coins necessary to make up the given target amount of change. The * solution will then be written to System.out. * * @param a_targetChangeAmount the target amount of change for which this * method is attempting to produce the minimum number of coins * @param a_chartDirectory directory to put the chart in * * @throws Exception// ww w . j av a2s. co m * * @author Neil Rotstan * @author Klaus Meffert * @since 1.0 */ public static void makeChangeForAmount(int a_targetChangeAmount, String a_chartDirectory) throws Exception { // Start with a DefaultConfiguration, which comes setup with the // most common settings. // ------------------------------------------------------------- Configuration conf = new DefaultConfiguration(); conf.setPreservFittestIndividual(true); conf.setKeepPopulationSizeConstant(false); // Set the fitness function we want to use, which is our // MinimizingMakeChangeFitnessFunction. We construct it with // the target amount of change passed in to this method. // --------------------------------------------------------- FitnessFunction myFunc = new MinimizingMakeChangeFitnessFunction(a_targetChangeAmount); // conf.setFitnessFunction(myFunc); conf.setBulkFitnessFunction(new BulkFitnessOffsetRemover(myFunc)); // Optionally, this example is working with DeltaFitnessEvaluator. // See MinimizingMakeChangeFitnessFunction for details! // --------------------------------------------------------------- // conf.setFitnessEvaluator(new DeltaFitnessEvaluator()); // Now we need to tell the Configuration object how we want our // Chromosomes to be setup. We do that by actually creating a // sample Chromosome and then setting it on the Configuration // object. As mentioned earlier, we want our Chromosomes to each // have four genes, one for each of the coin types. We want the // values (alleles) of those genes to be integers, which represent // how many coins of that type we have. We therefore use the // IntegerGene class to represent each of the genes. That class // also lets us specify a lower and upper bound, which we set // to sensible values for each coin type. // -------------------------------------------------------------- Gene[] sampleGenes = new Gene[4]; sampleGenes[0] = new IntegerGene(conf, 0, 3 * 10); // Quarters sampleGenes[1] = new IntegerGene(conf, 0, 2 * 10); // Dimes sampleGenes[2] = new IntegerGene(conf, 0, 1 * 10); // Nickels sampleGenes[3] = new IntegerGene(conf, 0, 4 * 10); // Pennies IChromosome sampleChromosome = new Chromosome(conf, sampleGenes); conf.setSampleChromosome(sampleChromosome); // Finally, we need to tell the Configuration object how many // Chromosomes we want in our population. The more Chromosomes, // the larger number of potential solutions (which is good for // finding the answer), but the longer it will take to evolve // the population (which could be seen as bad). // ------------------------------------------------------------ conf.setPopulationSize(80); // JFreeChart: setup DefaultCategoryDataset dataset = new DefaultCategoryDataset(); PlotOrientation or = PlotOrientation.VERTICAL; // Create random initial population of Chromosomes. // ------------------------------------------------ Genotype population = Genotype.randomInitialGenotype(conf); // Evolve the population. Since we don't know what the best answer // is going to be, we just evolve the max number of times. // --------------------------------------------------------------- for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) { population.evolve(); // JFreeChart: add current best fitness to chart double fitness = population.getFittestChromosome().getFitnessValue(); if (i % 3 == 0) { String s = String.valueOf(i); dataset.setValue(fitness, "Fitness", s); } } // Display the best solution we found. // ----------------------------------- IChromosome bestSolutionSoFar = population.getFittestChromosome(); System.out.println("The best solution has a fitness value of " + bestSolutionSoFar.getFitnessValue()); System.out.println("It contained the following: "); System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0) + " quarters."); System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1) + " dimes."); System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 2) + " nickels."); System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 3) + " pennies."); System.out.println("For a total of " + MinimizingMakeChangeFitnessFunction.amountOfChange(bestSolutionSoFar) + " cents in " + MinimizingMakeChangeFitnessFunction.getTotalNumberOfCoins(bestSolutionSoFar) + " coins."); // JFreeChart: Create chart JFreeChart chart = ChartFactory.createLineChart("JGAP: Evolution progress", "Evolution cycle", "Fitness value", dataset, or, true /*legend*/, true /*tooltips*/ , false /*urls*/); BufferedImage image = chart.createBufferedImage(640, 480); String imagefile = "chart.jpg"; FileOutputStream fo = new FileOutputStream(a_chartDirectory + imagefile); ChartUtilities.writeBufferedImageAsJPEG(fo, 0.7f, image); System.out.println("Chart written to image file " + a_chartDirectory + imagefile); }
From source file:com.sun.japex.report.ChartGenerator.java
/** * Create a chart for a single test case across all drivers. *///from w w w .j a v a2 s. com public JFreeChart createTrendChart(String testCaseName) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); final int size = _reports.size(); for (int i = 0; i < size; i++) { TestSuiteReport report = _reports.get(i); SimpleDateFormat formatter = _dateFormatter; // If previous or next are on the same day, include time if (i > 0 && onSameDate(report, _reports.get(i - 1))) { formatter = _dateTimeFormatter; } if (i + 1 < size && onSameDate(report, _reports.get(i + 1))) { formatter = _dateTimeFormatter; } List<TestSuiteReport.Driver> drivers = report.getDrivers(); for (TestSuiteReport.Driver driver : drivers) { TestSuiteReport.TestCase testCase = driver.getTestCase(testCaseName); if (testCase != null) { double value = testCase.getResult(); if (!Double.isNaN(value)) { dataset.addValue(value, driver.getName(), formatter.format(report.getDate().getTime())); } } } } JFreeChart chart = ChartFactory.createLineChart(testCaseName, "", "", dataset, PlotOrientation.VERTICAL, true, true, false); configureLineChart(chart); chart.setAntiAlias(true); return chart; }
From source file:edu.ucla.stat.SOCR.chart.demo.StatisticalLineChartDemo2.java
protected JFreeChart createLegend(CategoryDataset dataset) { // JFreeChart chart = ChartFactory.createAreaChart( JFreeChart chart = ChartFactory.createLineChart(chartTitle, // chart title domainLabel, // domain axis label rangeLabel, // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips false // urls );//from www. j ava 2s . c o m // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART... chart.setBackgroundPaint(Color.white); CategoryPlot plot = chart.getCategoryPlot(); StatisticalLineAndShapeRenderer renderer = new StatisticalLineAndShapeRenderer(true, false); renderer.setLegendItemLabelGenerator( new SOCRCategoryCellLabelGenerator(dataset, values_storage, SERIES_COUNT, CATEGORY_COUNT)); plot.setRenderer(renderer); return chart; }
From source file:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java
@Override public void onBeforeRender() { super.onBeforeRender(); Connection jdbcConnection = null; try {/*from w ww . j a v a2 s . c o m*/ if (report == null) throw new Exception("No report given to render diagram"); jdbcConnection = DatabaseUtils.getDatabaseConnection(report.getDataSource()); ResultSet resultSet = DatabaseUtils.getResultSet(jdbcConnection, report.getStatement(), parameters); ResultSetMetaData metaData = resultSet.getMetaData(); JFreeChart chart = null; resultSet.beforeFirst(); // Line chart - 1 numeric value if (report.getDiagram() == 0) { if (metaData.getColumnCount() != 1) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.1numvalues") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.addValue(resultSet.getDouble(1), metaData.getColumnName(1), String.valueOf(resultSet.getRow())); chart = ChartFactory.createLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new ResourceModel("dashboard.report.reportdiagram.image.row-label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); // XY Series chart - 2 numeric values } else if (report.getDiagram() == 1) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2numvalues") .wrapOnAssignment(this).getObject()); XYSeries series = new XYSeries(metaData.getColumnName(1) + " / " + metaData.getColumnName(2)); while (resultSet.next()) series.add(resultSet.getDouble(1), resultSet.getDouble(2)); chart = ChartFactory.createXYLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), metaData.getColumnName(2), new XYSeriesCollection(series), PlotOrientation.VERTICAL, true, true, true); // Category chart - 1 numeric value, 1 comparable value } else if (report.getDiagram() == 2) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), metaData.getColumnName(1) + " / " + metaData.getColumnName(2), resultSet.getString(2)); chart = new JFreeChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new CategoryPlot(dataset, new LabelAdaptingCategoryAxis(14, metaData.getColumnName(2)), new NumberAxis(metaData.getColumnName(1)), new CategoryStepRenderer(true))); // Pie chart - 1 numeric value, 1 comparable value (used as category) } else if ((report.getDiagram() == 3) || (report.getDiagram() == 4)) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultPieDataset dataset = new DefaultPieDataset(); while (resultSet.next()) dataset.setValue(resultSet.getString(2), resultSet.getDouble(1)); if (report.getDiagram() == 3) // Pie chart 2D chart = ChartFactory .createPieChart(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); else if (report.getDiagram() == 4) { // Pie chart 3D chart = ChartFactory .createPieChart3D(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); ((PiePlot3D) chart.getPlot()).setForegroundAlpha( Float.valueOf(new ResourceModel("dashboard.report.reportdiagram.image.alpha") .wrapOnAssignment(this).getObject())); } // Bar chart - 1 numeric value, 2 comparable values (used as category, series) } else if (report.getDiagram() == 5) { if ((metaData.getColumnCount() != 2) && (metaData.getColumnCount() != 3)) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.3values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), resultSet.getString(2), resultSet.getString(metaData.getColumnCount())); chart = ChartFactory.createBarChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(2), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); } int[] winSize = DashboardCfgDelegate.getInstance().getWindowSize("reportDiagramImage"); addOrReplace(new JFreeChartImage("diagram", chart, winSize[0], winSize[1])); final JFreeChart downloadableChart = chart; addOrReplace(new Link<Object>("diagram-download") { private static final long serialVersionUID = 1L; @Override public void onClick() { RequestCycle.get().setRequestTarget(new IRequestTarget() { public void respond(RequestCycle requestCycle) { WebResponse wr = (WebResponse) requestCycle.getResponse(); wr.setContentType("image/png"); wr.setHeader("content-disposition", "attachment;filename=diagram.png"); OutputStream os = wr.getOutputStream(); try { ImageIO.write(downloadableChart.createBufferedImage(800, 600), "png", os); os.close(); } catch (IOException e) { log.error(this.getClass().toString() + ": " + "respond: " + e.getMessage()); log.debug("Exception: ", e); } wr.close(); } @Override public void detach(RequestCycle arg0) { } }); } }.add(new Image("diagram-download-image", ImageManager.IMAGE_DASHBOARD_REPORT_DOWNLOAD) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.downloadlink")))); addOrReplace(new Image("diagram-print-image", ImageManager.IMAGE_DASHBOARD_REPORT_PRINT) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.printbutton"))); addOrReplace(new Label("error-message", "").setVisible(false)); addOrReplace(new Label("error-reason", "").setVisible(false)); } catch (Exception e) { log.error("Exception: " + e.getMessage()); addOrReplace(((DynamicDisplayPage) this.getPage()).new PlaceholderLink("diagram-download") .setVisible(false)); addOrReplace(new Image("diagram-print-image").setVisible(false)); addOrReplace(new Image("diagram").setVisible(false)); addOrReplace(new Label("error-message", new ResourceModel("dashboard.report.reportdiagram.statement.error").wrapOnAssignment(this) .getObject()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); addOrReplace(new Label("error-reason", e.getMessage()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); log.debug(getClass() + ": ", e); } finally { try { jdbcConnection.close(); } catch (Exception ignore) { } } }
From source file:br.com.OCTur.view.ClassificacaoController.java
@FXML private void tvCidadeMouseReleased(MouseEvent mouseEvent) { if (tvCidade.getSelectionModel().getSelectedItem() != null) { DefaultCategoryDataset dcdDados = new DefaultCategoryDataset(); Date inicio = DateFormatter.toDate(dpInicio.getValue()); Date fim = DateFormatter.toDate(dpFim.getValue()); Calendar inicioCalendar = Calendar.getInstance(); inicioCalendar.setTime(inicio);//ww w. j av a 2 s . c o m while (inicioCalendar.getTime().before(fim) || inicioCalendar.getTime().equals(fim)) { dcdDados.addValue( new PassagemDAO() .pegarPorDestinoInicioFim( tvCidade.getSelectionModel().getSelectedItem().getEntidade(), inicioCalendar.getTime(), inicioCalendar.getTime()) .stream().mapToDouble(Passagem::getNumeropessoas).sum(), "Pessoas", DateFormatter.toDay(inicioCalendar.getTime())); inicioCalendar.add(Calendar.DAY_OF_MONTH, 1); } JFreeChart jFreeChart = ChartFactory.createLineChart("", "", "", dcdDados, PlotOrientation.VERTICAL, false, false, false); ChartPanel chartPanel = new ChartPanel(jFreeChart); snGrafico.setContent(chartPanel); } }
From source file:org.bench4Q.console.ui.section.P_WIPSSection.java
private JPanel printWIPSPic() throws IOException { double[][] value = wipsSmooth(); for (int i = 0; i < value[0].length; ++i) { value[0][i] = i;/* w ww . j ava 2 s .c o m*/ // value[1][i] = webInteractionThroughput[i];. } DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset(); String series1 = "Basic"; String series2 = "real"; // String series2 = "High"; for (int i = 0; i < value[0].length; ++i) { defaultcategorydataset.addValue(value[1][i], series1, new Integer((int) value[0][i])); defaultcategorydataset.addValue(webInteractionThroughput[0][i], series2, new Integer((int) value[0][i])); } JFreeChart chart = ChartFactory.createLineChart("WIPS = " + WIPS, "time", "WIPS", defaultcategorydataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(Color.white); CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); categoryplot.setBackgroundPaint(Color.WHITE); categoryplot.setRangeGridlinePaint(Color.white); NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); numberaxis.setAutoRangeIncludesZero(true); LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer(); lineandshaperenderer.setShapesVisible(false); lineandshaperenderer.setSeriesStroke(0, new BasicStroke(2.0F, 1, 1, 1.0F, new float[] { 1F, 1F }, 0.0F)); lineandshaperenderer.setSeriesFillPaint(0, Color.BLACK); lineandshaperenderer.setSeriesStroke(1, new BasicStroke(2.0F, 1, 0, 2.0F, new float[] { 1F, 10000F }, 0.0F)); lineandshaperenderer.setSeriesFillPaint(0, Color.darkGray); return new ChartPanel(chart); }
From source file:Controlador.ControladorLecturas.java
public JInternalFrame graficoHumedadSuelo() { DefaultCategoryDataset defaultCategoryDataset = new DefaultCategoryDataset(); for (Object row : vectorHumedadSuelo()) { int grados = Integer.parseInt(((Vector) row).elementAt(0).toString()); String rowKey = "Sensor 1"; String columnKey = ((Vector) row).elementAt(1).toString(); defaultCategoryDataset.addValue(grados, rowKey, columnKey); }//from ww w . j a v a2 s .co m JFreeChart jFreeChart = ChartFactory.createLineChart(null, "Hora", "Humedad", defaultCategoryDataset, PlotOrientation.VERTICAL, true, true, true); ChartPanel chartPanel = new ChartPanel(jFreeChart); JInternalFrame jInternalFrame = new JInternalFrame("Grafico de Humedad del Suelo", true, true, true, true); jInternalFrame.add(chartPanel, BorderLayout.CENTER); jInternalFrame.pack(); return jInternalFrame; }
From source file:Interface.Graphe.java
public Graphe(String applicationTitle, String chartTitle) { super(applicationTitle); JFreeChart lineChart = ChartFactory.createLineChart(chartTitle, "Annes", "Montant", createDataset(), PlotOrientation.VERTICAL, true, true, false); ChartPanel chartPanel = new ChartPanel(lineChart); chartPanel.setPreferredSize(new java.awt.Dimension(600, 400)); setContentPane(chartPanel);/* ww w. ja v a 2 s .c om*/ }