List of usage examples for org.jfree.chart.plot XYPlot setForegroundAlpha
public void setForegroundAlpha(float alpha)
From source file:MSUmpire.DIA.MixtureModelKDESemiParametric.java
public void GeneratePlot(String pngfile) throws IOException { String modelfile = FilenameUtils.getFullPath(pngfile) + "/" + FilenameUtils.getBaseName(pngfile) + "_ModelPoints.txt"; FileWriter writer = new FileWriter(modelfile); double[] IDObs = new double[IDEmpiricalDist.getN()]; double[] DecoyObs = new double[DecoyEmpiricalDist.getN()]; for (int i = 0; i < IDEmpiricalDist.getN(); i++) { IDObs[i] = IDEmpiricalDist.getObs(i); }/*from w w w . jav a 2 s .com*/ for (int i = 0; i < DecoyEmpiricalDist.getN(); i++) { DecoyObs[i] = DecoyEmpiricalDist.getObs(i); } XYSeries model1 = new XYSeries("Incorrect matches"); XYSeries model2 = new XYSeries("Correct matches"); XYSeries model3 = new XYSeries("All target hits"); writer.write("UScore\tModel\tCorrect\tDecoy\n"); for (int i = 0; i < NoBinPoints; i++) { model1.add(model_kde_x[i], decoy_kde_y[i]); model2.add(model_kde_x[i], correct_kde_y[i]); model3.add(model_kde_x[i], model_kde_y[i]); writer.write(model_kde_x[i] + "\t" + model_kde_y[i] + "\t" + correct_kde_y[i] + "\t" + decoy_kde_y[i] + "\n"); } writer.close(); MixtureModelProb = new float[NoBinPoints + 1][3]; float positiveaccu = 0f; float negativeaccu = 0f; MixtureModelProb[0][0] = (float) model2.getMaxX() + Float.MIN_VALUE; MixtureModelProb[0][1] = 1f; MixtureModelProb[0][2] = 1f; for (int i = 1; i < NoBinPoints + 1; i++) { double positiveNumber = correct_kde_y[NoBinPoints - i]; double negativeNumber = decoy_kde_y[NoBinPoints - i]; MixtureModelProb[i][0] = (float) model_kde_x[NoBinPoints - i]; positiveaccu += positiveNumber; negativeaccu += negativeNumber; MixtureModelProb[i][2] = 0.999999f * (float) (positiveNumber / (negativeNumber + positiveNumber)); MixtureModelProb[i][1] = 0.999999f * (float) (positiveaccu / (negativeaccu + positiveaccu)); } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(model1); dataset.addSeries(model2); dataset.addSeries(model3); HistogramDataset histogramDataset = new HistogramDataset(); histogramDataset.setType(HistogramType.SCALE_AREA_TO_1); histogramDataset.addSeries("ID hits", IDObs, 100); histogramDataset.addSeries("Decoy hits", DecoyObs, 100); //histogramDataset.addSeries("Model hits", ModelObs, 100); JFreeChart chart = ChartFactory.createHistogram(FilenameUtils.getBaseName(pngfile), "Score", "Hits", histogramDataset, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = chart.getXYPlot(); NumberAxis domain = (NumberAxis) plot.getDomainAxis(); domain.setRange(min, max); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setForegroundAlpha(0.8f); chart.setBackgroundPaint(Color.white); XYLineAndShapeRenderer render = new XYLineAndShapeRenderer(); plot.setDataset(1, dataset); plot.setRenderer(1, render); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); try { ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600); } catch (IOException e) { } }
From source file:com.rapidminer.gui.plotter.charts.HistogramChart.java
@Override protected void updatePlotter() { prepareData();// w w w . j a v a 2 s .co m String maxClassesProperty = ParameterService .getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_COLORS_CLASSLIMIT); int maxClasses = 20; try { if (maxClassesProperty != null) { maxClasses = Integer.parseInt(maxClassesProperty); } } catch (NumberFormatException e) { // LogService.getGlobal().log("Deviation plotter: cannot parse property 'rapidminer.gui.plotter.colors.classlimit', using maximal 20 different classes.", // LogService.WARNING); LogService.getRoot().log(Level.WARNING, "com.rapidminer.gui.plotter.charts.HistogramChart.parsing_property_error"); } int categoryCount = this.histogramDataset.getSeriesCount(); boolean createLegend = categoryCount > 0 && categoryCount < maxClasses && this.drawLegend; JFreeChart chart = ChartFactory.createHistogram(null, // title "Value", "Frequency", histogramDataset, PlotOrientation.VERTICAL, createLegend, true, // tooltips false); // urls XYPlot plot = chart.getXYPlot(); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); plot.setBackgroundPaint(Color.WHITE); plot.setForegroundAlpha(this.opaqueness); XYBarRenderer renderer = new XYBarRenderer(); if (histogramDataset.getSeriesCount() == 1) { renderer.setSeriesPaint(0, ColorProvider.reduceColorBrightness(Color.RED)); renderer.setSeriesFillPaint(0, ColorProvider.reduceColorBrightness(Color.RED)); } else { for (int i = 0; i < histogramDataset.getSeriesCount(); i++) { Color color = getColorProvider(true) .getPointColor((double) i / (double) (histogramDataset.getSeriesCount() - 1)); renderer.setSeriesPaint(i, color); renderer.setSeriesFillPaint(i, color); } } renderer.setBarPainter(new RapidXYBarPainter()); // renderer.setBarPainter(new StandardXYBarPainter()); renderer.setDrawBarOutline(true); renderer.setShadowVisible(false); plot.setRenderer(renderer); plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD); plot.getRangeAxis().setTickLabelFont(LABEL_FONT); plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD); plot.getDomainAxis().setTickLabelFont(LABEL_FONT); setRange(plot.getDomainAxis()); // display correct x-Axis labels int count = histogramDataset.getSeriesCount(); if (count > 0) { String key = histogramDataset.getSeriesKey(0).toString(); int index = this.dataTable.getColumnIndex(key); if (index >= 0) { // Correctly displays nominal values on x-axis if (count == 1 && this.dataTable.isNominal(index)) { String[] values = new String[dataTable.getNumberOfValues(index)]; for (int i = 0; i < values.length; i++) { values[i] = dataTable.mapIndex(index, i); } plot.setDomainAxis(new SymbolAxis(key, values)); } // Correctly displays dates on x-axis if (this.dataTable.isDateTime(index)) { boolean applyDateAxis = true; if (count > 1) { for (int i = 1; i < count; i++) { index = this.dataTable.getColumnIndex(histogramDataset.getSeriesKey(i).toString()); if (index < 0 || !this.dataTable.isDateTime(index)) { applyDateAxis = false; break; } } } if (applyDateAxis) { DateAxis dateAxis = new DateAxis(); dateAxis.setDateFormatOverride(Tools.DATE_TIME_FORMAT.get()); plot.setDomainAxis(dateAxis); } } } // rotate labels if (isLabelRotating()) { plot.getDomainAxis().setTickLabelsVisible(true); plot.getDomainAxis().setVerticalTickLabels(true); } } // set the background color for the chart... chart.setBackgroundPaint(Color.white); // legend settings LegendTitle legend = chart.getLegend(); if (legend != null) { legend.setPosition(RectangleEdge.TOP); legend.setFrame(BlockBorder.NONE); legend.setHorizontalAlignment(HorizontalAlignment.LEFT); legend.setItemFont(LABEL_FONT); } AbstractChartPanel panel = getPlotterPanel(); if (panel == null) { panel = createPanel(chart); } else { panel.setChart(chart); } // Disable zooming for Histogram-Charts panel.setRangeZoomable(false); panel.setDomainZoomable(false); // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!! panel.getChartRenderingInfo().setEntityCollection(null); }
From source file:edu.ucla.stat.SOCR.chart.demo.DifferenceChartDemo1.java
/** * Creates a chart./* w w w. j av a2 s . c o m*/ * * @param dataset the dataset. * * @return The chart. */ protected JFreeChart createChart(XYDataset dataset) { JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, domainLabel, rangeLabel, dataset, !legendPanelOn, // legend true, // tool tips false // URLs ); chart.setBackgroundPaint(Color.white); XYPlot plot = chart.getXYPlot(); plot.setRenderer(new XYDifferenceRenderer(Color.green, Color.red, false)); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); XYItemRenderer renderer = plot.getRenderer(); renderer.setLegendItemLabelGenerator(new SOCRXYSeriesLabelGenerator()); ValueAxis domainAxis = new DateAxis("Time"); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.0); plot.setDomainAxis(domainAxis); plot.setForegroundAlpha(0.5f); //setXSummary(dataset) X is time; return chart; }
From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java
/** * Generates a SparkLine Time Area Chart. * @param key//from w w w .j a va 2 s.co m * @param stats * @param startTime * @param endTime * @return chart */ private JFreeChart generateSparklineAreaChart(String key, String color, Statistic[] stats, long startTime, long endTime, int dataPoints) { Color backgroundColor = getBackgroundColor(); XYDataset dataset = populateData(key, stats, startTime, endTime, dataPoints); JFreeChart chart = ChartFactory.createXYAreaChart(null, // chart title null, // xaxis label null, // yaxis label dataset, // data PlotOrientation.VERTICAL, false, // include legend false, // tooltips? false // URLs? ); chart.setBackgroundPaint(backgroundColor); chart.setBorderVisible(false); chart.setBorderPaint(null); XYPlot plot = (XYPlot) chart.getPlot(); plot.setForegroundAlpha(1.0f); plot.setDomainGridlinesVisible(false); plot.setDomainCrosshairVisible(false); plot.setRangeCrosshairVisible(false); plot.setBackgroundPaint(backgroundColor); plot.setRangeGridlinesVisible(false); GraphDefinition graphDef = GraphDefinition.getDefinition(color); Color plotColor = graphDef.getInlineColor(0); plot.getRenderer().setSeriesPaint(0, plotColor); plot.getRenderer().setBaseItemLabelsVisible(false); plot.getRenderer().setBaseOutlinePaint(backgroundColor); plot.setOutlineStroke(null); plot.setDomainGridlinePaint(null); NumberAxis xAxis = (NumberAxis) chart.getXYPlot().getDomainAxis(); xAxis.setLabel(null); xAxis.setTickLabelsVisible(true); xAxis.setTickMarksVisible(true); xAxis.setAxisLineVisible(false); xAxis.setNegativeArrowVisible(false); xAxis.setPositiveArrowVisible(false); xAxis.setVisible(false); NumberAxis yAxis = (NumberAxis) chart.getXYPlot().getRangeAxis(); yAxis.setTickLabelsVisible(false); yAxis.setTickMarksVisible(false); yAxis.setAxisLineVisible(false); yAxis.setNegativeArrowVisible(false); yAxis.setPositiveArrowVisible(false); yAxis.setVisible(false); return chart; }
From source file:weka.gui.beans.JFreeChartOffscreenChartRenderer.java
/** * Render histogram(s) (numeric attribute) or bar chart (nominal attribute). * Some implementations may not be able to render more than one histogram/bar * on the same chart - the implementation can either throw an exception or * just process the first series in this case. * /*ww w. ja va 2s . c o m*/ * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param attsToPlot the attribute to plot corresponding to the Instances in * the series list * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ public BufferedImage renderHistogram(int width, int height, List<Instances> series, String attToPlot, List<String> additionalArgs) throws Exception { String plotTitle = "Bar Chart"; String userTitle = getOption(additionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; String colorAtt = getOption(additionalArgs, "-color"); String pareto = getOption(additionalArgs, "-pareto"); boolean doPareto = false; if (pareto != null && pareto.length() == 0 && series.size() == 1) { doPareto = true; } if (series.size() == 1 && colorAtt != null && colorAtt.length() > 0) { int colIndex = getIndexOfAttribute(series.get(0), colorAtt); if (colIndex >= 0 && series.get(0).attribute(colIndex).isNominal() && !doPareto) { // split single series out into multiple instances objects - one // per class series = splitToClasses(series.get(0), colIndex); for (Instances insts : series) { insts.setClassIndex(colIndex); } } } Instances masterInstances = series.get(0); int attIndex = getIndexOfAttribute(masterInstances, attToPlot); if (attIndex < 0) { attIndex = 0; } if (!(series.get(0).attribute(attIndex).isNominal() || series.get(0).attribute(attIndex).isRelationValued())) { doPareto = false; } // Do a pareto chart if (doPareto) { final DefaultKeyedValues data = new DefaultKeyedValues(); AttributeStats attStats = masterInstances.attributeStats(attIndex); double[] attValFreqs = attStats.nominalWeights; for (int i = 0; i < attValFreqs.length; i++) { Number freq = new Double(attValFreqs[i]); data.addValue(masterInstances.attribute(attIndex).value(i), freq); } data.sortByValues(SortOrder.DESCENDING); final KeyedValues cumulative = DataUtilities.getCumulativePercentages(data); final CategoryDataset dataset = DatasetUtilities .createCategoryDataset(masterInstances.attribute(attIndex).name(), data); final JFreeChart chart = ChartFactory.createBarChart(plotTitle, masterInstances.attribute(attIndex).name(), "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false); final CategoryPlot plot = chart.getCategoryPlot(); final CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLowerMargin(0.02); domainAxis.setUpperMargin(0.02); LineAndShapeRenderer renderer2 = new LineAndShapeRenderer(); CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative", cumulative); final NumberAxis axis2 = new NumberAxis("Percent"); axis2.setNumberFormatOverride(NumberFormat.getPercentInstance()); // plot. plot.setRangeAxis(1, axis2); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.mapDatasetToRangeAxis(1, 1); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); chart.setBackgroundPaint(java.awt.Color.white); BufferedImage image = chart.createBufferedImage(width, height); return image; } boolean seriesAreClasses = false; int classIndex = masterInstances.classIndex(); if (classIndex >= 0 && !masterInstances.attribute(classIndex).isNumeric() && !masterInstances.attribute(classIndex).isRelationValued() && masterInstances.attributeStats(classIndex).distinctCount == 1) { // series correspond to class labels (assume that subsequent series only // contain instances of one class)... seriesAreClasses = true; } // bar chart for a nominal attribute if (masterInstances.attribute(attIndex).isNominal() || masterInstances.attribute(attIndex).isString()) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // do the master series String masterSeriesTitle = masterInstances.relationName(); if (seriesAreClasses) { for (int i = 0; i < masterInstances.numInstances(); i++) { Instance current = masterInstances.instance(i); if (!current.isMissing(classIndex)) { masterSeriesTitle = current.stringValue(classIndex); break; } } } AttributeStats attStats = masterInstances.attributeStats(attIndex); double[] attValFreqs = attStats.nominalWeights; for (int i = 0; i < attValFreqs.length; i++) { Number freq = new Double(attValFreqs[i]); dataset.addValue(freq, masterSeriesTitle, masterInstances.attribute(attIndex).value(i)); } // any subsequent series for (int i = 1; i < series.size(); i++) { Instances nextSeries = series.get(i); String seriesTitle = nextSeries.relationName(); if (seriesAreClasses) { for (int j = 0; j < nextSeries.numInstances(); j++) { Instance current = nextSeries.instance(j); if (!current.isMissing(classIndex)) { seriesTitle = current.stringValue(classIndex); break; } } attStats = nextSeries.attributeStats(attIndex); attValFreqs = attStats.nominalWeights; for (int j = 0; j < attValFreqs.length; j++) { Number freq = new Double(attValFreqs[j]); dataset.addValue(freq, seriesTitle, nextSeries.attribute(attIndex).value(j)); } } } JFreeChart chart = null; if (series.size() == 1) { chart = ChartFactory.createBarChart(plotTitle, masterInstances.attribute(attIndex).name(), "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false); } else { chart = ChartFactory.createStackedBarChart(plotTitle, masterInstances.attribute(attIndex).name(), "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false); } chart.setBackgroundPaint(java.awt.Color.white); BufferedImage image = chart.createBufferedImage(width, height); return image; } else { // histogram for numeric attributes HistogramDataset dataset = new HistogramDataset(); // combine all series in order to get overall std dev, and range Instances temp = new Instances(masterInstances); for (int i = 1; i < series.size(); i++) { Instances additional = series.get(i); for (Instance tempI : additional) { temp.add(tempI); } } AttributeStats stats = temp.attributeStats(attIndex); Stats numericStats = stats.numericStats; double intervalWidth = 3.49 * numericStats.stdDev * StrictMath.pow(temp.numInstances(), (-1.0 / 3.0)); double range = numericStats.max - numericStats.min; int numBins = StrictMath.max(1, (int) StrictMath.round(range / intervalWidth)); // do the master series String masterSeriesTitle = masterInstances.relationName(); if (seriesAreClasses) { for (int i = 0; i < masterInstances.numInstances(); i++) { Instance current = masterInstances.instance(i); if (!current.isMissing(current.classAttribute())) { masterSeriesTitle = current.stringValue(current.classAttribute()); break; } } } // have to set min, max and num bins (using heuristic from AttSummPanel). // Make sure // to set series length to num instances - num missing values for att stats = masterInstances.attributeStats(attIndex); /* * numericStats = stats.numericStats; //numericStats.calculateDerived(); * intervalWidth = StrictMath.max(1, 3.49 * numericStats.stdDev * * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0))); */ double[] seriesVals = new double[masterInstances.numInstances() - stats.missingCount]; int count = 0; for (int i = 0; i < masterInstances.numInstances(); i++) { Instance current = masterInstances.instance(i); if (!current.isMissing(attIndex)) { seriesVals[count++] = current.value(attIndex); } } dataset.addSeries(masterSeriesTitle, seriesVals, numBins, numericStats.min, numericStats.max); // any subsequent series for (int i = 1; i < series.size(); i++) { Instances nextSeries = series.get(i); String seriesTitle = nextSeries.relationName(); if (seriesAreClasses) { for (int j = 0; j < nextSeries.numInstances(); j++) { Instance current = nextSeries.instance(j); if (!current.isMissing(nextSeries.classAttribute())) { seriesTitle = current.stringValue(nextSeries.classAttribute()); break; } } } stats = nextSeries.attributeStats(attIndex); /* * numericStats = stats.numericStats; // * numericStats.calculateDerived(); intervalWidth = StrictMath.max(1, * 3.49 * numericStats.stdDev * * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0))); range = * numericStats.max - numericStats.min; numBins = StrictMath.max(1, * (int) StrictMath.round(range / intervalWidth)); */ seriesVals = new double[nextSeries.numInstances() - stats.missingCount]; count = 0; for (int j = 0; j < nextSeries.numInstances(); j++) { Instance current = nextSeries.instance(j); if (!current.isMissing(attIndex)) { seriesVals[count++] = current.value(attIndex); } } dataset.addSeries(seriesTitle, seriesVals, numBins, numericStats.min, numericStats.max); } JFreeChart chart = ChartFactory.createHistogram(plotTitle, masterInstances.attribute(attIndex).name(), null, dataset, PlotOrientation.VERTICAL, true, false, false); // chart.setBackgroundPaint(java.awt.Color.white); XYPlot xyplot = (XYPlot) chart.getPlot(); xyplot.setForegroundAlpha(0.50F); XYBarRenderer xybarrenderer = (XYBarRenderer) xyplot.getRenderer(); xybarrenderer.setDrawBarOutline(false); xybarrenderer.setShadowVisible(false); BufferedImage image = chart.createBufferedImage(width, height); return image; } }
From source file:edu.dlnu.liuwenpeng.ChartFactory.ChartFactory.java
/** * Creates an area chart using an {@link XYDataset}. * <P> /* w ww . j a va2s .c om*/ * The chart object returned by this method uses an {@link XYPlot} instance * as the plot, with a {@link NumberAxis} for the domain axis, a * {@link NumberAxis} as the range axis, and a {@link XYAreaRenderer} as * the renderer. * * @param title the chart title (<code>null</code> permitted). * @param xAxisLabel a label for the X-axis (<code>null</code> permitted). * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted). * @param dataset the dataset for the chart (<code>null</code> permitted). * @param orientation the plot orientation (horizontal or vertical) * (<code>null</code> NOT permitted). * @param legend a flag specifying whether or not a legend is required. * @param tooltips configure chart to generate tool tips? * @param urls configure chart to generate URLs? * * @return An XY area chart. */ public static JFreeChart createXYAreaChart(String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) { if (orientation == null) { throw new IllegalArgumentException("Null 'orientation' argument."); } NumberAxis xAxis = new NumberAxis(xAxisLabel); xAxis.setAutoRangeIncludesZero(false); NumberAxis yAxis = new NumberAxis(yAxisLabel); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null); plot.setOrientation(orientation); plot.setForegroundAlpha(0.5f); XYToolTipGenerator tipGenerator = null; if (tooltips) { tipGenerator = new StandardXYToolTipGenerator(); } XYURLGenerator urlGenerator = null; if (urls) { urlGenerator = new StandardXYURLGenerator(); } plot.setRenderer(new XYAreaRenderer(XYAreaRenderer.AREA, tipGenerator, urlGenerator)); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend); return chart; }
From source file:KIDLYFactory.java
/** * Creates an area chart using an {@link XYDataset}. * <P>/* ww w .j a v a 2 s .co m*/ * The chart object returned by this method uses an {@link XYPlot} instance * as the plot, with a {@link NumberAxis} for the domain axis, a * {@link NumberAxis} as the range axis, and a {@link XYAreaRenderer} as * the renderer. * * @param title the chart title (<code>null</code> permitted). * @param xAxisLabel a label for the X-axis (<code>null</code> permitted). * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted). * @param dataset the dataset for the chart (<code>null</code> permitted). * @param orientation the plot orientation (horizontal or vertical) * (<code>null</code> NOT permitted). * @param legend a flag specifying whether or not a legend is required. * @param tooltips configure chart to generate tool tips? * @param urls configure chart to generate URLs? * * @return An XY area chart. */ public static JFreeChart createXYAreaChart(String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) { if (orientation == null) { throw new IllegalArgumentException("Null 'orientation' argument."); } NumberAxis xAxis = new NumberAxis(xAxisLabel); xAxis.setAutoRangeIncludesZero(false); NumberAxis yAxis = new NumberAxis(yAxisLabel); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null); plot.setOrientation(orientation); plot.setForegroundAlpha(0.5f); XYToolTipGenerator tipGenerator = null; if (tooltips) { tipGenerator = new StandardXYToolTipGenerator(); } XYURLGenerator urlGenerator = null; if (urls) { urlGenerator = new StandardXYURLGenerator(); } plot.setRenderer(new XYAreaRenderer(XYAreaRenderer.AREA, tipGenerator, urlGenerator)); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend); currentTheme.apply(chart); return chart; }
From source file:org.locationtech.udig.processingtoolbox.tools.BubbleChartDialog.java
private void updateChart(SimpleFeatureCollection features, String xField, String yField, String sizeField) { // 1. Create a single plot containing both the scatter and line XYPlot plot = new XYPlot(); plot.setOrientation(PlotOrientation.VERTICAL); plot.setBackgroundPaint(java.awt.Color.WHITE); plot.setDomainPannable(false);//from w w w . ja va 2 s. c o m plot.setRangePannable(false); plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD); plot.setDomainCrosshairVisible(false); plot.setRangeCrosshairVisible(false); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setForegroundAlpha(0.75f); // 2. Setup Scatter plot // Create the bubble chart data, renderer, and axis int fontStyle = java.awt.Font.BOLD; FontData fontData = getShell().getDisplay().getSystemFont().getFontData()[0]; NumberAxis xPlotAxis = new NumberAxis(xField); // Independent variable xPlotAxis.setLabelFont(new Font(fontData.getName(), fontStyle, 12)); xPlotAxis.setTickLabelFont(new Font(fontData.getName(), fontStyle, 10)); NumberAxis yPlotAxis = new NumberAxis(yField); // Dependent variable yPlotAxis.setLabelFont(new Font(fontData.getName(), fontStyle, 12)); yPlotAxis.setTickLabelFont(new Font(fontData.getName(), fontStyle, 10)); XYItemRenderer plotRenderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_RANGE_AXIS); plotRenderer.setSeriesPaint(0, java.awt.Color.ORANGE); // dot plotRenderer.setBaseItemLabelGenerator(new BubbleXYItemLabelGenerator()); plotRenderer.setBaseToolTipGenerator(new StandardXYZToolTipGenerator()); plotRenderer .setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER)); // Set the bubble chart data, renderer, and axis into plot plot.setDataset(0, getBubbleChartData(features, xField, yField, sizeField)); xPlotAxis.setAutoRangeIncludesZero(false); xPlotAxis.setAutoRange(false); double differUpper = minMaxVisitor.getMaxX() - minMaxVisitor.getAverageX(); double differLower = minMaxVisitor.getAverageX() - minMaxVisitor.getMinX(); double gap = Math.abs(differUpper - differLower); if (differUpper > differLower) { xPlotAxis.setRange(minMaxVisitor.getMinX() - gap, minMaxVisitor.getMaxX()); } else { xPlotAxis.setRange(minMaxVisitor.getMinX(), minMaxVisitor.getMaxX() + gap); } yPlotAxis.setAutoRangeIncludesZero(false); yPlotAxis.setAutoRange(false); differUpper = minMaxVisitor.getMaxY() - minMaxVisitor.getAverageY(); differLower = minMaxVisitor.getAverageY() - minMaxVisitor.getMinY(); gap = Math.abs(differUpper - differLower); if (differUpper > differLower) { yPlotAxis.setRange(minMaxVisitor.getMinY() - gap, minMaxVisitor.getMaxY()); } else { yPlotAxis.setRange(minMaxVisitor.getMinY(), minMaxVisitor.getMaxY() + gap); } plot.setRenderer(0, plotRenderer); plot.setDomainAxis(0, xPlotAxis); plot.setRangeAxis(0, yPlotAxis); // Map the scatter to the first Domain and first Range plot.mapDatasetToDomainAxis(0, 0); plot.mapDatasetToRangeAxis(0, 0); // 3. Setup line // Create the line data, renderer, and axis XYItemRenderer lineRenderer = new XYLineAndShapeRenderer(true, false); // Lines only lineRenderer.setSeriesPaint(0, java.awt.Color.GRAY); lineRenderer.setSeriesPaint(1, java.awt.Color.GRAY); lineRenderer.setSeriesPaint(2, java.awt.Color.GRAY); // Set the line data, renderer, and axis into plot NumberAxis xLineAxis = new NumberAxis(EMPTY); xLineAxis.setTickMarksVisible(false); xLineAxis.setTickLabelsVisible(false); NumberAxis yLineAxis = new NumberAxis(EMPTY); yLineAxis.setTickMarksVisible(false); yLineAxis.setTickLabelsVisible(false); XYSeriesCollection lineDataset = new XYSeriesCollection(); // AverageY XYSeries horizontal = new XYSeries("AverageY"); //$NON-NLS-1$ horizontal.add(xPlotAxis.getRange().getLowerBound(), minMaxVisitor.getAverageY()); horizontal.add(xPlotAxis.getRange().getUpperBound(), minMaxVisitor.getAverageY()); lineDataset.addSeries(horizontal); // AverageX XYSeries vertical = new XYSeries("AverageX"); //$NON-NLS-1$ vertical.add(minMaxVisitor.getAverageX(), yPlotAxis.getRange().getLowerBound()); vertical.add(minMaxVisitor.getAverageX(), yPlotAxis.getRange().getUpperBound()); lineDataset.addSeries(vertical); plot.setDataset(1, lineDataset); plot.setRenderer(1, lineRenderer); plot.setDomainAxis(1, xLineAxis); plot.setRangeAxis(1, yLineAxis); // Map the line to the second Domain and second Range plot.mapDatasetToDomainAxis(1, 0); plot.mapDatasetToRangeAxis(1, 0); // 4. Setup Selection NumberAxis xSelectionAxis = new NumberAxis(EMPTY); xSelectionAxis.setTickMarksVisible(false); xSelectionAxis.setTickLabelsVisible(false); NumberAxis ySelectionAxis = new NumberAxis(EMPTY); ySelectionAxis.setTickMarksVisible(false); ySelectionAxis.setTickLabelsVisible(false); XYItemRenderer selectionRenderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_RANGE_AXIS); selectionRenderer.setSeriesPaint(0, java.awt.Color.RED); // dot selectionRenderer.setSeriesOutlinePaint(0, java.awt.Color.RED); plot.setDataset(2, new DefaultXYZDataset2()); plot.setRenderer(2, selectionRenderer); plot.setDomainAxis(2, xSelectionAxis); plot.setRangeAxis(2, ySelectionAxis); // Map the scatter to the second Domain and second Range plot.mapDatasetToDomainAxis(2, 0); plot.mapDatasetToRangeAxis(2, 0); // 5. Finally, Create the chart with the plot and a legend java.awt.Font titleFont = new Font(fontData.getName(), fontStyle, 20); JFreeChart chart = new JFreeChart(EMPTY, titleFont, plot, false); chart.setBackgroundPaint(java.awt.Color.WHITE); chart.setBorderVisible(false); chartComposite.setChart(chart); chartComposite.forceRedraw(); }
From source file:MSUmpire.DIA.TargetMatchScoring.java
public void MixtureModeling() throws IOException { if (libTargetMatches.isEmpty()) { return;/*from w w w . j av a 2 s . c o m*/ } int IDNo = 0; int decoyNo = 0; int modelNo = 0; double IDmean = 0d; double Decoymean = 0d; for (UmpireSpecLibMatch match : libIDMatches) { if (match.BestHit != null) { IDNo++; IDmean += match.BestHit.UmpireScore; } } decoyNo = decoyModelingList.size(); for (PeakGroupScore peakGroupScore : decoyModelingList) { Decoymean += peakGroupScore.UmpireScore; } for (UmpireSpecLibMatch match : libTargetMatches) { //modelNo+= match.TargetHits.size(); if (match.BestMS1Hit != null) { modelNo++; } if (match.BestMS2Hit != null) { modelNo++; } } Decoymean /= decoyNo; IDmean /= IDNo; PVector[] points = new PVector[modelNo]; PVector[] centroids = new PVector[2]; int idx = 0; for (UmpireSpecLibMatch match : libTargetMatches) { if (match.BestMS1Hit != null) { points[idx] = new PVector(1); points[idx].array[0] = match.BestMS1Hit.UmpireScore; idx++; } if (match.BestMS2Hit != null) { points[idx] = new PVector(1); points[idx].array[0] = match.BestMS2Hit.UmpireScore; idx++; } // for(PeakGroupScore peakGroupScore : match.TargetHits){ // points[idx] = new PVector(1); // points[idx].array[0] = match.BestMS2Hit.UmpireScore; // idx++; // } } MixtureModel mmc; centroids[0] = new PVector(1); centroids[0].array[0] = Decoymean; centroids[1] = new PVector(1); centroids[1].array[0] = IDmean; Vector<PVector>[] clusters = KMeans.run(points, 2, centroids); MixtureModel mm = ExpectationMaximization1D.initialize(clusters); mmc = ExpectationMaximization1D.run(points, mm); DecimalFormat df = new DecimalFormat("#.####"); Logger.getRootLogger() .debug("----------------------------------------------------------------------------------------"); Logger.getRootLogger().debug("No. of modeling points=" + modelNo); Logger.getRootLogger().debug("ID hits mean=" + df.format(IDmean)); Logger.getRootLogger().debug("Decoy hits mean=" + df.format(Decoymean)); //System.out.print("T-test: p-value=" + df.format(model.ttest.pValue).toString() + "\n"); Logger.getRootLogger() .debug("Incorrect hits model mean=" + df.format(((PVector) mmc.param[0]).array[0]) + " variance=" + df.format(((PVector) mmc.param[0]).array[1]) + " weight=" + df.format(mmc.weight[0])); Logger.getRootLogger() .debug("Correct hits model mean=" + df.format(((PVector) mmc.param[1]).array[0]) + " variance=" + df.format(((PVector) mmc.param[1]).array[1]) + " weight=" + df.format(mmc.weight[1])); if (((PVector) mmc.param[0]).array[0] > ((PVector) mmc.param[1]).array[0]) { return; } float max = (float) (((PVector) mmc.param[1]).array[0] + 4 * Math.sqrt(((PVector) mmc.param[1]).array[1])); float min = (float) (((PVector) mmc.param[0]).array[0] - 4 * Math.sqrt(((PVector) mmc.param[0]).array[1])); IDNo = 0; decoyNo = 0; modelNo = 0; for (PeakGroupScore peakGroupScore : decoyModelingList) { if (peakGroupScore.UmpireScore > min && peakGroupScore.UmpireScore < max) { decoyNo++; } } for (UmpireSpecLibMatch match : libIDMatches) { if (match.BestHit != null && match.BestHit.UmpireScore > min && match.BestHit.UmpireScore < max) { IDNo++; } } for (UmpireSpecLibMatch match : libTargetMatches) { //targetNo += match.TargetHits.size(); //decoyNo += match.DecoyHits.size(); if (match.BestMS1Hit != null && match.BestMS1Hit.UmpireScore > min && match.BestMS1Hit.UmpireScore < max) { modelNo++; } if (match.BestMS2Hit != null && match.BestMS2Hit.UmpireScore > min && match.BestMS2Hit.UmpireScore < max) { modelNo++; } //modelNo += match.TargetHits.size(); } double[] IDObs = new double[IDNo]; double[] DecoyObs = new double[decoyNo]; double[] ModelObs = new double[modelNo]; idx = 0; int didx = 0; int midx = 0; for (UmpireSpecLibMatch match : libIDMatches) { if (match.BestHit != null && match.BestHit.UmpireScore > min && match.BestHit.UmpireScore < max) { IDObs[idx++] = match.BestHit.UmpireScore; } } for (PeakGroupScore peakGroupScore : decoyModelingList) { if (peakGroupScore.UmpireScore > min && peakGroupScore.UmpireScore < max) { DecoyObs[didx++] = peakGroupScore.UmpireScore; } } for (UmpireSpecLibMatch match : libTargetMatches) { // for(PeakGroupScore peak : match.TargetHits){ // ModelObs[midx++]=peak.UmpireScore; // } if (match.BestMS1Hit != null && match.BestMS1Hit.UmpireScore > min && match.BestMS1Hit.UmpireScore < max) { ModelObs[midx++] = match.BestMS1Hit.UmpireScore; } if (match.BestMS2Hit != null && match.BestMS2Hit.UmpireScore > min && match.BestMS2Hit.UmpireScore < max) { ModelObs[midx++] = match.BestMS2Hit.UmpireScore; } } String pngfile = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename) + "_" + LibID + "_LibMatchModel.png"; XYSeries model1 = new XYSeries("Incorrect matches"); XYSeries model2 = new XYSeries("Correct matches"); XYSeries model3 = new XYSeries("All target hits"); String modelfile = FilenameUtils.getFullPath(pngfile) + "/" + FilenameUtils.getBaseName(pngfile) + "_ModelPoints.txt"; FileWriter writer = new FileWriter(modelfile); writer.write("UScore\tModel\tCorrect\tDecoy\n"); int NoPoints = 1000; double[] model_kde_x = new double[NoPoints]; float intv = (max - min) / NoPoints; PVector point = new PVector(2); for (int i = 0; i < NoPoints; i++) { point.array[0] = max - i * intv; model_kde_x[i] = point.array[0]; point.array[1] = mmc.EF.density(point, mmc.param[0]) * mmc.weight[0]; model1.add(point.array[0], point.array[1]); point.array[1] = mmc.EF.density(point, mmc.param[1]) * mmc.weight[1]; model2.add(point.array[0], point.array[1]); } KernelDensityEstimator kde = new KernelDensityEstimator(); kde.SetData(ModelObs); double[] model_kde_y = kde.Density(model_kde_x); for (int i = 0; i < NoPoints; i++) { if (model_kde_x[i] > min && model_kde_x[i] < max) { point.array[0] = max - i * intv; model_kde_x[i] = point.array[0]; model3.add(model_kde_x[i], model_kde_y[i]); writer.write(point.array[0] + "\t" + mmc.EF.density(point, mmc.param[0]) * mmc.weight[0] + "\t" + mmc.EF.density(point, mmc.param[1]) * mmc.weight[1] + "\t" + model_kde_y[i] + "\n"); } } writer.close(); MixtureModelProb = new float[NoPoints + 1][3]; float positiveaccu = 0f; float negativeaccu = 0f; MixtureModelProb[0][0] = (float) model2.getMaxX() + Float.MIN_VALUE; MixtureModelProb[0][1] = 1f; MixtureModelProb[0][2] = 1f; for (int i = 1; i < NoPoints + 1; i++) { float positiveNumber = model2.getY(NoPoints - i).floatValue(); float negativeNumber = model1.getY(NoPoints - i).floatValue(); MixtureModelProb[i][0] = model2.getX(NoPoints - i).floatValue(); positiveaccu += positiveNumber; negativeaccu += negativeNumber; MixtureModelProb[i][2] = positiveNumber / (negativeNumber + positiveNumber); MixtureModelProb[i][1] = positiveaccu / (negativeaccu + positiveaccu); } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(model1); dataset.addSeries(model2); dataset.addSeries(model3); HistogramDataset histogramDataset = new HistogramDataset(); histogramDataset.setType(HistogramType.SCALE_AREA_TO_1); histogramDataset.addSeries("ID hits", IDObs, 100); histogramDataset.addSeries("Decoy hits", DecoyObs, 100); //histogramDataset.addSeries("Model hits", ModelObs, 100); JFreeChart chart = ChartFactory.createHistogram(FilenameUtils.getBaseName(pngfile), "Score", "Hits", histogramDataset, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = chart.getXYPlot(); NumberAxis domain = (NumberAxis) plot.getDomainAxis(); domain.setRange(min, max); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setForegroundAlpha(0.8f); chart.setBackgroundPaint(Color.white); XYLineAndShapeRenderer render = new XYLineAndShapeRenderer(); // render.setSeriesPaint(0, Color.DARK_GRAY); // render.setSeriesPaint(1, Color.DARK_GRAY); // render.setSeriesPaint(2, Color.GREEN); // render.setSeriesShape(0, new Ellipse2D.Double(0, 0, 2, 2)); // render.setSeriesShape(1, new Ellipse2D.Double(0, 0, 2, 2)); // render.setSeriesShape(2, new Ellipse2D.Double(0, 0, 2.5f, 2.5f)); // render.setSeriesStroke(1, new BasicStroke(1.0f)); // render.setSeriesStroke(0, new BasicStroke(1.0f)); // render.setSeriesStroke(2, new BasicStroke(2.0f)); plot.setDataset(1, dataset); plot.setRenderer(1, render); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); try { ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600); } catch (IOException e) { } }
From source file:org.jfree.chart.demo.DifferenceChartDemo2.java
/** * Creates a chart./*from w w w .ja v a 2 s . co m*/ * * @param dataset the dataset. * * @return The chart. */ private JFreeChart createChart(final XYDataset dataset) { final JFreeChart chart = ChartFactory.createTimeSeriesChart("Daylight Hours - London, UK", "Date", "Time", dataset, true, // legend true, // tool tips false // URLs ); chart.setBackgroundPaint(Color.white); final XYDifferenceRenderer renderer = new XYDifferenceRenderer(Color.blue, Color.blue, false); renderer.setStroke(new BasicStroke(2.0f)); renderer.setSeriesPaint(0, Color.yellow); renderer.setSeriesPaint(1, Color.red); final XYPlot plot = chart.getXYPlot(); plot.setRenderer(renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0)); final DateAxis domainAxis = new DateAxis("Time"); domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.0); plot.setDomainAxis(domainAxis); plot.setForegroundAlpha(0.5f); final Color c = new Color(255, 60, 24, 63); final Marker bst = new IntervalMarker(new Day(28, 3, 2004).getFirstMillisecond(), new Day(30, 10, 2004).getFirstMillisecond(), c, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel("British Summer Time"); bst.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.BASELINE_RIGHT); plot.addDomainMarker(bst, Layer.BACKGROUND); final DateAxis rangeAxis = new DateAxis("Time"); rangeAxis.setLowerMargin(0.15); rangeAxis.setUpperMargin(0.15); plot.setRangeAxis(rangeAxis); return chart; }