Java Code Examples for org.jfree.chart.ChartUtilities

The following are top voted examples for showing how to use org.jfree.chart.ChartUtilities. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: passatuto   File: SimilarityMatrix.java   View source code 7 votes vote down vote up
public static void writeRankVSScore(File outputFile, List<SimilarityMatrix> matrices, int length, String add) throws Exception{		
	final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();
	for(SimilarityMatrix m:matrices){
		int[][] sortedIndizes=m.getIndizesOfSortedScores();
		List<Double>[] scoreList=new List[Math.min(length,sortedIndizes[0].length)];
		for(int i=0;i<scoreList.length;i++)scoreList[i]=new ArrayList<Double>();
		for(int i=0;i<sortedIndizes.length;i++){
			int l=0;
			for(int j=0;j<sortedIndizes[i].length;j++){
				double v=m.getSimilarityValue(i,sortedIndizes[i][j]);
				if(!Double.isNaN(v)){
					scoreList[l].add(v);
					l++;						
				}
				if(l>=scoreList.length)break;
			}			
		}
		for(int i=0;i<scoreList.length;i++)
			dataset.add(scoreList[i], m.getMethodsQueryAndDBString(), i);

	}

	JFreeChart chart=ChartFactory.createBoxAndWhiskerChart("Whiskerplot", "Ranks", "Scores", dataset, true);
	ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+sep+add+"RankVSScore_"+getMethodsQueryStringFromList(matrices)+".jpg"), chart, Math.min(2000,length*100), 1000);
}
 
Example 2
Project: kurento-java   File: ChartWriter.java   View source code 7 votes vote down vote up
public void drawChart(String filename, int width, int height) throws IOException {
  // Create plot
  NumberAxis xAxis = new NumberAxis(xAxisLabel);
  NumberAxis yAxis = new NumberAxis(yAxisLabel);
  XYSplineRenderer renderer = new XYSplineRenderer();
  XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
  plot.setBackgroundPaint(Color.lightGray);
  plot.setDomainGridlinePaint(Color.white);
  plot.setRangeGridlinePaint(Color.white);
  plot.setAxisOffset(new RectangleInsets(4, 4, 4, 4));

  // Create chart
  JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
  ChartUtilities.applyCurrentTheme(chart);
  ChartPanel chartPanel = new ChartPanel(chart, false);

  // Draw png
  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  Graphics graphics = bi.getGraphics();
  chartPanel.setBounds(0, 0, width, height);
  chartPanel.paint(graphics);
  ImageIO.write(bi, "png", new File(filename));
}
 
Example 3
Project: passatuto   File: Plot.java   View source code 6 votes vote down vote up
public static void writeRankVSPercentage(File outputFile, String add, List<ResultList>[] resultsOriginal, List<List<ResultList>>[] resultsDecoy, int length) throws Exception{

		for(List<ResultList> o:resultsOriginal){
			for(List<List<ResultList>> ds:resultsDecoy){
				String name="RankVSpercentage";
				if(ds.size()>1)name+="Mean";
				Map<String,int[]> numbers=new TreeMap<String,int[]>();
				for(List<ResultList> d:ds){
					List<ResultList> merged=ResultList.mergeResults(new List[]{o,d});
					for(int i=0;i<merged.size();i++){
						ResultList rl=merged.get(i);
						for(int j=0;j<Math.min(length,rl.results.size());j++){
							String key=rl.query.getDB()+"-"+rl.results.get(j).getDB();
							if(!numbers.containsKey(key))numbers.put(key, new int[length]);
							numbers.get(key)[j]=numbers.get(key)[j]+1;
						}
					}
				}

				String fileName="";
				final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
				for(Entry<String, int[]> n:numbers.entrySet()){
					double all=0;
					for(int i=0;i<n.getValue().length;i++){
						dataset.addValue(n.getValue()[i], n.getKey(), Integer.toString(i));
					}
					fileName+=n.getKey()+"---";
				}

				fileName=fileName.substring(0,fileName.length()-3);

				final JFreeChart chart = ChartFactory.createBarChart("Boxplot","Ranks","Percentage",dataset);
				ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+"\\"+name+"_"+fileName+add+".jpg"), chart, Math.min(2000,length*100), 1000);
			}
		}
	}
 
Example 4
Project: passatuto   File: HitStatistic.java   View source code 6 votes vote down vote up
public static void writeROCCurves(File outputFile, TreeMap<String, HitStatistic> hits) throws Exception{

		XYSeriesCollection dataset = new XYSeriesCollection();
		
		for(Entry<String, HitStatistic> e:hits.entrySet()){
			File txtFile=new File(outputFile.getAbsolutePath().replaceAll(".jpg","_"+e.getKey().split("-")[2]+".txt"));
			BufferedWriter bw=new BufferedWriter(new FileWriter(txtFile));
			XYSeries series= new XYSeries(e.getKey());
			bw.write("false positive rate\tsensitivity");
			bw.newLine();
			List<double[]> roc=e.getValue().getROCAverage();
			for(double[] r:roc){
				bw.write(r[0]+"\t"+r[1]);
				bw.newLine();
				series.add(r[0],r[1]);
			}
			dataset.addSeries(series);
			bw.close();
		}
		
		
		final JFreeChart chart =ChartFactory.createXYLineChart("ROCCurve",  "false positive rate", "sensitivity", dataset);
		ChartUtilities.saveChartAsJPEG(outputFile, chart, 1000, 400);
	}
 
Example 5
Project: rapidminer   File: AbstractChartPanel.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 * 
 * @throws IOException
 *             if there is an I/O error.
 */

@Override
public void doSaveAs() throws IOException {

	JFileChooser fileChooser = new JFileChooser();
	fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
	ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"), ".png");
	fileChooser.addChoosableFileFilter(filter);

	int option = fileChooser.showSaveDialog(this);
	if (option == JFileChooser.APPROVE_OPTION) {
		String filename = fileChooser.getSelectedFile().getPath();
		if (isEnforceFileExtensions()) {
			if (!filename.endsWith(".png")) {
				filename = filename + ".png";
			}
		}
		ChartUtilities.saveChartAsPNG(new File(filename), this.chart, getWidth(), getHeight());
	}

}
 
Example 6
Project: EditCalculateAndChart   File: SaveAs_Action.java   View source code 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
         try{
            if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION){
                   String SelectedFileName = fileChooser.getSelectedFile().getAbsolutePath();
             if(SelectedFileName.toUpperCase().endsWith(".JPG")||
                SelectedFileName.toUpperCase().endsWith(".JPEG")){                     
                   ChartUtilities.saveChartAsJPEG(new File(SelectedFileName),TEdit,500,500);
                                                        return;
                  }

             if(SelectedFileName.toUpperCase().endsWith(".PNG")){
                   ChartUtilities.saveChartAsPNG(new File(SelectedFileName),TEdit,500,500);
                                                        return; 
                      }
                   ChartUtilities.saveChartAsPNG(new File(SelectedFileName+".png"),TEdit,500,500);
                    
              }
          }
        catch(Exception Ex){
               System.out.println(Ex.toString());   
          }
}
 
Example 7
Project: java-course   File: GlasanjeGrafikaServlet.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    List<PollOption> results = null;
    try {
        Long pollId = (Long) req.getSession().getAttribute("pollID");
        results = DAOProvider.getDao().getPollOptions(pollId);
    } catch (Exception ex) {
        results = new ArrayList<>();
    }

    JFreeChart chart = DBUtility.getChart(results);
    ChartUtilities.writeChartAsPNG(resp.getOutputStream(), chart, 700, 400);
}
 
Example 8
Project: java-course   File: GlasanjeGrafikaServlet.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String resultFile = req.getServletContext().getRealPath(
            "/WEB-INF/glasanje-rezultati.txt");
    String definitionFile = req.getServletContext().getRealPath(
            "/WEB-INF/glasanje-definicija.txt");

    List<Band> results = ServerUtilty
            .getResults(definitionFile, resultFile);

    JFreeChart chart = ServerUtilty.getChart(results);
    ChartUtilities.writeChartAsPNG(resp.getOutputStream(), chart, 700, 400);
    resp.getOutputStream().flush();
}
 
Example 9
Project: parabuild-ci   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the ChartRenderingInfo object which can be used to generate
 * an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated (<code>null</code> permitted).
 * @param session  the HttpSession of the client.
 *
 * @return the filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
                                    ChartRenderingInfo info, HttpSession session)
        throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");   
    }
    ServletUtilities.createTempDir();
    File tempFile = File.createTempFile(
        ServletUtilities.tempFilePrefix, ".png", 
        new File(System.getProperty("java.io.tmpdir"))
    );
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    ServletUtilities.registerChartForDeletion(tempFile, session);
    return tempFile.getName();

}
 
Example 10
Project: parabuild-ci   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a JPEG format file in the temporary directory and
 * populates the ChartRenderingInfo object which can be used to generate
 * an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart
 * @param height  the height of the chart
 * @param info  the ChartRenderingInfo object to be populated
 * @param session  the HttpSession of the client
 *
 * @return the filename of the chart saved in the temporary directory
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsJPEG(JFreeChart chart, int width, int height,
                                     ChartRenderingInfo info, HttpSession session)
        throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");   
    }
    
    ServletUtilities.createTempDir();
    File tempFile = File.createTempFile(
        ServletUtilities.tempFilePrefix, 
        ".jpeg", new File(System.getProperty("java.io.tmpdir"))
    );
    ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
    ServletUtilities.registerChartForDeletion(tempFile, session);

    return tempFile.getName();

}
 
Example 11
Project: parabuild-ci   File: ChartComposite.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(canvas.getShell(), SWT.SAVE);
    String[] extensions = { "*.png" };
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, 
                canvas.getSize().x, canvas.getSize().y);
    }
}
 
Example 12
Project: parabuild-ci   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to 
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated 
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by 
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");   
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png", 
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}
 
Example 13
Project: DIA-Umpire-Maven   File: RTAlignedPepIonMapping.java   View source code 6 votes vote down vote up
private void GenerateRTMapPNG(XYSeriesCollection xySeriesCollection, XYSeries series, float R2) throws IOException {
    new File(Workfolder + "/RT_Mapping/").mkdir();
    String pngfile = Workfolder + "/RT_Mapping/" + FilenameUtils.getBaseName(LCMSA.mzXMLFileName).substring(0, Math.min(120, FilenameUtils.getBaseName(LCMSA.mzXMLFileName).length() - 1)) + "_" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName).substring(0, Math.min(120, FilenameUtils.getBaseName(LCMSB.mzXMLFileName).length() - 1)) + "_RT.png";

    XYSeries smoothline = new XYSeries("RT fitting curve");
    for (XYZData data : regression.PredictYList) {
        smoothline.add(data.getX(), data.getY());
    }
    xySeriesCollection.addSeries(smoothline);
    xySeriesCollection.addSeries(series);
    JFreeChart chart = ChartFactory.createScatterPlot("Retention time mapping: R2=" + R2, "RT:" + FilenameUtils.getBaseName(LCMSA.mzXMLFileName), "RT:" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName), xySeriesCollection,
            PlotOrientation.VERTICAL, true, true, false);
    XYPlot xyPlot = (XYPlot) chart.getPlot();
    xyPlot.setDomainCrosshairVisible(true);
    xyPlot.setRangeCrosshairVisible(true);

    XYItemRenderer renderer = xyPlot.getRenderer();
    renderer.setSeriesPaint(1, Color.blue);
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setSeriesShape(1, new Ellipse2D.Double(0, 0, 3, 3));
    renderer.setSeriesStroke(1, new BasicStroke(3.0f));
    renderer.setSeriesStroke(0, new BasicStroke(3.0f));
    xyPlot.setBackgroundPaint(Color.white);
    ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
}
 
Example 14
Project: ccu-historian   File: ChartComposite.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example 15
Project: CanReg5   File: Tools.java   View source code 6 votes vote down vote up
static String writeJChartToFile(JFreeChart chart, File file, FileTypes fileType) throws IOException, DocumentException {
    String fileName = file.getPath();
    switch (fileType) {
        case svg:
            Tools.exportChartAsSVG(chart, new Rectangle(1000, 1000), file);
            break;
        case pdf:
            Tools.exportChartAsPDF(chart, new Rectangle(500, 400), file);
            break;
        case jchart:
            break;
        case csv:
            Tools.exportChartAsCSV(chart, file);
            break;
        default:
            ChartUtilities.saveChartAsPNG(file, chart, 1000, 1000);
            break;
    }
    return fileName;
}
 
Example 16
Project: plot-plugin   File: Plot.java   View source code 6 votes vote down vote up
/**
 * Generates and writes the plotpipeline's clickable map to the response output
 * stream.
 *
 * @param req
 *            the incoming request
 * @param rsp
 *            the response stream
 * @throws IOException
 */
public void plotGraphMap(StaplerRequest req, StaplerResponse rsp)
        throws IOException {
    if ( ChartUtil.awtProblemCause != null) {
        // not available. send out error message
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
        return;
    }
    setWidth(req);
    setHeight(req);
    setNumBuilds(req);
    setRightBuildNum(req);
    setHasLegend(req);
    setTitle(req);
    setStyle(req);
    setUseDescr(req);
    generatePlot(false);
    ChartRenderingInfo info = new ChartRenderingInfo();
    plot.createBufferedImage(getWidth(), getHeight(), info);
    rsp.setContentType("text/plain;charset=UTF-8");
    rsp.getWriter().println(
            ChartUtilities.getImageMap(getCsvFileName(), info));
}
 
Example 17
Project: aya-lang   File: ChartComposite.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example 18
Project: businesshorizon2   File: DeterResultPanel.java   View source code 6 votes vote down vote up
private static JFreeChart createChart() {
    final CategoryAxis domainAxis = new CategoryAxis("");
    final NumberAxis rangeAxis = new NumberAxis("");
    final IntervalBarRenderer renderer = new IntervalBarRenderer();
    renderer.setBaseToolTipGenerator(new IntervalCategoryToolTipGenerator());
    renderer.setBaseToolTipGenerator((dataset, row, column) -> {
        final IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
        return icd.getRowKey(row) + ": " + (icd.getEndValue(row, column).doubleValue() - icd.getStartValue(row, column).doubleValue());
    });

    final CategoryPlot plot = new CategoryPlot(null, domainAxis, rangeAxis, renderer);
    final JFreeChart chart = new JFreeChart("Unternehmenswert", plot);
    plot.setDomainGridlinesVisible(true);
    plot.setRangePannable(true);
    ChartUtilities.applyCurrentTheme(chart);
    return chart;

}
 
Example 19
Project: PanamaHitek_Arduino   File: PanamaHitek_ThermometerChart.java   View source code 6 votes vote down vote up
public void buildPlot1() {
    setColorLimits();
    dataset = new DefaultValueDataset(30);
    ThermometerPlot thermometerplot = new ThermometerPlot(dataset);
    thermometerplot.setRange(plotBottonLimit, plotTopLimit);
    thermometerplot.setUnits(ThermometerPlot.UNITS_CELCIUS);
    thermometerplot.setSubrange(0, greenBottomLimit, greenTopLimit);
    thermometerplot.setSubrangePaint(0, Color.green);
    thermometerplot.setSubrange(1, yellowBottomLimit, yellowTopLimit);
    thermometerplot.setSubrangePaint(1, Color.yellow);
    thermometerplot.setSubrange(2, redBottomLimit, redTopLimit);
    thermometerplot.setSubrangePaint(2, Color.red);
    JFreeChart jfreechart = new JFreeChart(plotTitle, thermometerplot);
    ChartUtilities.applyCurrentTheme(jfreechart);
    add(new ChartPanel(jfreechart));
}
 
Example 20
Project: rapidminer-studio   File: AbstractChartPanel.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 * 
 * @throws IOException
 *             if there is an I/O error.
 */

@Override
public void doSaveAs() throws IOException {

	JFileChooser fileChooser = new JFileChooser();
	fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
	ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"), ".png");
	fileChooser.addChoosableFileFilter(filter);

	int option = fileChooser.showSaveDialog(this);
	if (option == JFileChooser.APPROVE_OPTION) {
		String filename = fileChooser.getSelectedFile().getPath();
		if (isEnforceFileExtensions()) {
			if (!filename.endsWith(".png")) {
				filename = filename + ".png";
			}
		}
		ChartUtilities.saveChartAsPNG(new File(filename), this.chart, getWidth(), getHeight());
	}

}
 
Example 21
Project: jmodeltest2   File: HtmlReporter.java   View source code 6 votes vote down vote up
private static void buildChart(File mOutputFile, InformationCriterion ic) {
		
		/* This line prevents Swing exceptions on headless environments */
		if (GraphicsEnvironment.isHeadless()) { return; }
		
		int width = 500;
		int height = 300;
		try {
			if (!IMAGES_DIR.exists()) {
				IMAGES_DIR.mkdir();
			}
			ChartUtilities.saveChartAsPNG(new File(IMAGES_DIR.getPath() + File.separator + mOutputFile.getName() + "_rf_" + ic + ".png"), 
					RFHistogram.buildRFHistogram(ic),
					width, height);
			ChartUtilities.saveChartAsPNG(new File(IMAGES_DIR.getPath() + File.separator + mOutputFile.getName() + "_eu_" + ic + ".png"), 
					RFHistogram.buildEuclideanHistogram(ic),
					width, height);
		} catch (IOException e) {
//			e.printStackTrace();
		}
	}
 
Example 22
Project: JGrafix   File: TelaComparativos.java   View source code 6 votes vote down vote up
private void salvarJPEG() {
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {
            ChartUtilities.saveChartAsJPEG(file,
                    chartPanel.getChart(),
                    chartPanel.getWidth(),
                    chartPanel.getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 23
Project: greenpepper   File: AbstractChartBuilder.java   View source code 6 votes vote down vote up
public String getChartMap(String chartMapId)
		throws IOException
{
	StringWriter writer = new StringWriter();
	PrintWriter pw = new PrintWriter(writer);

	try
	{
		ChartUtilities.writeImageMap(pw, chartMapId, chartRenderingInfo,
									 new StandardToolTipTagFragmentGenerator(),
									 new StandardURLTagFragmentGenerator());
	}
	finally
	{
		IOUtil.closeQuietly(pw);
	}

	return writer.toString();
}
 
Example 24
Project: greenpepper   File: AbstractChartBuilder.java   View source code 6 votes vote down vote up
/**
 * <p>getChartMap.</p>
 *
 * @param chartMapId a {@link java.lang.String} object.
 * @return a {@link java.lang.String} object.
 * @throws java.io.IOException if any.
 */
public String getChartMap(String chartMapId)
		throws IOException
{
	StringWriter writer = new StringWriter();
	PrintWriter pw = new PrintWriter(writer);

	try
	{
		ChartUtilities.writeImageMap(pw, chartMapId, chartRenderingInfo,
									 new StandardToolTipTagFragmentGenerator(),
									 new StandardURLTagFragmentGenerator());
	}
	finally
	{
		IOUtil.closeQuietly(pw);
	}

	return writer.toString();
}
 
Example 25
Project: HTML5_WebSite   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png",
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}
 
Example 26
Project: nyla   File: JFreeChartFacade.java   View source code 6 votes vote down vote up
/**
 * 
 * @return JPEG version of chart
 */
public byte[] getBytes()
{
	try
	{
		JFreeChart chart = createChart();
		
		
		ByteArrayOutputStream chartOut =  new ByteArrayOutputStream(this.byteArrayBufferSize);
		
		ChartUtilities.writeChartAsJPEG(chartOut, chart, width, height);
		
		return chartOut.toByteArray();
	} 
	catch (IOException e)
	{
		throw new SystemException(Debugger.stackTrace(e));
	}
	
}
 
Example 27
Project: PI   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png",
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}
 
Example 28
Project: kandy   File: ChartGenerator.java   View source code 6 votes vote down vote up
public void jpgLineChartTerminationRate(Integer percentTerminations[], List<Float> reliabilities)
        throws IOException {

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int j = 0; j < reliabilities.size(); j++) {
        dataset.addValue(percentTerminations[j], "early termination rate", reliabilities.get(j));
    }
    JFreeChart lineChartObject = ChartFactory.createLineChart(
            "Percent early termination rate of reliability estimation",
            "Reliability Lower Bound (Slb)", "Percent early termination rate",
            dataset, PlotOrientation.VERTICAL,
            true, true, false);

    int width = 640;
    /* Width of the image */

    int height = 480;
    /* Height of the image */

    String fileName = "earlyTerminationRate.jpeg";
    File lineChart = new File(fileName);
    ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height);
    logger.debug(fileName + " created");
}
 
Example 29
Project: kandy   File: ChartGenerator.java   View source code 6 votes vote down vote up
public void jpgLineChartCostPRE(BigDecimal[] relativeErrors, List<Float> reliabilities) throws IOException {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int j = 0; j < reliabilities.size(); j++) {
            dataset.addValue(relativeErrors[j], "", reliabilities.get(j));
        }
        JFreeChart lineChartObject = ChartFactory.createLineChart(
                "Percent relative error of CostEstimation",
                "Reliability Lower Bound (Slb)", "Percent relative Error",
                dataset, PlotOrientation.VERTICAL,
                true, true, false);

        int width = 640;
        /* Width of the image */

        int height = 480;
        /* Height of the image */

        String fileName = "costRelativeError.jpeg";
        File lineChart = new File(fileName);
        ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height);
        logger.debug(fileName + " created");
    }
 
Example 30
Project: jmetrik   File: NonparametricCurvePanel.java   View source code 6 votes vote down vote up
public void savePlots(String path)throws IOException{
        File dir = new File(path);
        if(!dir.exists()) dir.mkdirs();

        //Will Save in a way that an OS will list them in selected order but omits the TCC
//        int index=1;
//        for(String s : names){
//            JFreeChart c = charts.get(s);
//            String n = "a"+index+"-"+s;
//            ChartUtilities.saveChartAsJPEG(new File(dir.getAbsolutePath()+"/"+n+".jpg"), c, width, height);
//            index++;
//        }

        for(String s : charts.keySet()){
            JFreeChart c = charts.get(s);
            ChartUtilities.saveChartAsJPEG(new File(dir.getAbsolutePath()+"/"+s+".jpg"), c, width, height);
        }
    }
 
Example 31
Project: JMongoCounter   File: Window.java   View source code 6 votes vote down vote up
private void setupChart() {
    this.data = new TimeSeries("Counts");

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(this.data);

    DateAxis domain = new DateAxis("Time");
    domain.setAutoRange(true);
    NumberAxis range = new NumberAxis("Count");

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setBaseShapesVisible(false);
    renderer.setBaseSeriesVisibleInLegend(false);

    XYPlot plot = new XYPlot(dataset, domain, range, renderer);

    this.chart = new JFreeChart("Mongo Counts", plot);
    ChartUtilities.applyCurrentTheme(this.chart);
}
 
Example 32
Project: JDeSurvey   File: StatisticsController.java   View source code 6 votes vote down vote up
/**
 * Controller that handles the chart generation for a question statistics
 * @param surveyDefinitionId
 * @param pageOrder
 * @param questionOrder
 * @param recordCount
 * @param response
 */
@Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"})
@RequestMapping(value="/chart/{surveyDefinitionId}/{questionId}")
public void generatePieChart(@PathVariable("surveyDefinitionId")  Long surveyDefinitionId,
							 @PathVariable("questionId")  Long questionId, 
							 HttpServletResponse response) {
	try {
		response.setContentType("image/png");
		long recordCount  = surveyService.surveyStatistic_get(surveyDefinitionId).getSubmittedCount();
		PieDataset pieDataSet= createDataset(questionId,recordCount);
		JFreeChart chart = createChart(pieDataSet, "");
		ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 340 ,200);
		response.getOutputStream().close();
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 33
Project: nabs   File: ChartComposite.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(canvas.getShell(), SWT.SAVE);
    String[] extensions = { "*.png" };
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, 
                canvas.getSize().x, canvas.getSize().y);
    }
}
 
Example 34
Project: nabs   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to 
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated 
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by 
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");   
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png", 
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}
 
Example 35
Project: blacksmith   File: TimeSeriesReportGenerator.java   View source code 6 votes vote down vote up
public static void generate(ClusterTimeSeriesReport report, String reportDir, String fileName) throws IOException {
   File root = new File(reportDir);
   if (!root.exists()) {
      if (!root.mkdirs()) {
         log.warn("Could not create root dir : " + root.getAbsolutePath()
               + " This might result in reports not being generated");
      } else {
         log.info("Created root file: " + root);
      }
   }
   File chartFile = new File(root, fileName + ".png");
   Utils.backupFile(chartFile);

   ChartUtilities.saveChartAsPNG(chartFile, createChart(report), 1024, 768);

   log.info("Chart saved as " + chartFile);
}
 
Example 36
Project: blacksmith   File: LocalChartGenerator.java   View source code 6 votes vote down vote up
public void generateChart(String dir) throws Exception {
   long nrReads = 0;
   long nrWrites = 0;
   if(reportDesc.getItems().size() > 0) {
      for (ReportItem item : reportDesc.getItems()) {
         getData.addValue(item.getReadsPerSec(), item.description(), "GET");
         nrReads += item.getNoReads();
         putData.addValue(item.getWritesPerSec(), item.description(), "PUT");
         nrWrites += item.getNoWrites();
      }
      File localGetFile = new File(dir, "local_gets_" + reportDesc.getReportName() + ".png");
      Utils.backupFile(localGetFile);

      ChartUtilities.saveChartAsPNG(localGetFile, createChart("Report: Comparing Cache GET (READ) performance", getData, (int) (nrReads / reportDesc.getItems().size()), "(GETS)"), 800, 800);

      File localPutFile = new File(dir, "local_puts_" + reportDesc.getReportName() + ".png");
      Utils.backupFile(localPutFile);

      ChartUtilities.saveChartAsPNG(localPutFile, createChart("Report: Comparing Cache PUT (WRITE) performance", putData, (int) (nrWrites / reportDesc.getItems().size()), "(PUTS)"), 800, 800);
   }
}
 
Example 37
Project: ECG-Viewer   File: ChartComposite.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example 38
Project: entity-system-benchmarks   File: ChartWriterFactory.java   View source code 6 votes vote down vote up
private static void generateChart(String benchmark, DefaultCategoryDataset dataset, int benchmarkCount) {
	JFreeChart chart = ChartFactory.createBarChart(
			benchmark, "framework", "throughput", dataset,
			PlotOrientation.HORIZONTAL, true, false, false);

	CategoryPlot plot = chart.getCategoryPlot();
	BarRenderer renderer = (BarRenderer) plot.getRenderer();
	renderer.setItemMargin(0);
	notSoUglyPlease(chart);
	
	String pngFile = getOutputName(benchmark);
	
	try {
		int height = 100 + benchmarkCount * 20;
		ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 700, height);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 39
Project: astor   File: ChartComposite.java   View source code 6 votes vote down vote up
/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
            SWT.SAVE);
    String[] extensions = {"*.png"};
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
                this.canvas.getSize().x, this.canvas.getSize().y);
    }
}
 
Example 40
Project: astor   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the {@link ChartRenderingInfo} object which can be used to
 * generate an HTML image map.
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated
 *              (<code>null</code> permitted).
 * @param session  the HttpSession of the client (if <code>null</code>, the
 *                 temporary file is marked as "one-time" and deleted by
 *                 the {@link DisplayChart} servlet right after it is
 *                 streamed to the client).
 *
 * @return The filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
        ChartRenderingInfo info, HttpSession session) throws IOException {

    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
        prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile = File.createTempFile(prefix, ".png",
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
        ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();

}