List of usage examples for org.jfree.chart.plot XYPlot setRangeGridlinesVisible
public void setRangeGridlinesVisible(boolean visible)
From source file:msi.gama.outputs.layers.charts.ChartJFreeChartOutputScatter.java
@Override public void initChart(final IScope scope, final String chartname) { super.initChart(scope, chartname); final XYPlot pp = (XYPlot) chart.getPlot(); pp.setDomainGridlinePaint(axesColor); pp.setRangeGridlinePaint(axesColor); pp.setDomainCrosshairPaint(axesColor); pp.setRangeCrosshairPaint(axesColor); pp.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); pp.setDomainCrosshairVisible(false); pp.setRangeCrosshairVisible(false);//from w ww .ja va 2 s . co m pp.getDomainAxis().setAxisLinePaint(axesColor); pp.getDomainAxis().setTickLabelFont(getTickFont()); pp.getDomainAxis().setLabelFont(getLabelFont()); if (textColor != null) { pp.getDomainAxis().setLabelPaint(textColor); pp.getDomainAxis().setTickLabelPaint(textColor); } NumberAxis axis = (NumberAxis) pp.getRangeAxis(); axis = formatYAxis(scope, axis); pp.setRangeAxis(axis); if (ytickunit > 0) { ((NumberAxis) pp.getRangeAxis()).setTickUnit(new NumberTickUnit(ytickunit)); pp.setRangeGridlinesVisible(true); } else pp.setRangeGridlinesVisible(GamaPreferences.Displays.CHART_GRIDLINES.getValue()); // resetAutorange(scope); if (getType() == ChartOutput.SERIES_CHART) { if (xlabel == null) xlabel = "time"; } if (getType() == ChartOutput.XY_CHART) { } if (getType() == ChartOutput.SCATTER_CHART) { } if (!this.getXTickValueVisible(scope)) { pp.getDomainAxis().setTickMarksVisible(false); pp.getDomainAxis().setTickLabelsVisible(false); } }
From source file:com.jtstand.swing.StatsPanel.java
public JFreeChart getChartTime() { TreeMap<String, List<TestStepInstance>> s = getGroupedSteps(getFilteringIterator()); if (s == null || s.size() == 0) { return null; }/*from www . ja va 2 s.c o m*/ TimeSeriesCollection dataset = new TimeSeriesCollection(); for (Iterator<String> en = s.keySet().iterator(); en.hasNext();) { String groupName = en.next(); List<TestStepInstance> stps = s.get(groupName); // TimeSeries pop = new TimeSeries(groupName, Millisecond.class); TimeSeries pop = new TimeSeries(groupName); for (Iterator<TestStepInstance> it = stps.iterator(); it.hasNext();) { TestStepInstance step = it.next(); Number num = getNumber(step); if (num != null) { switch (chartMode) { case STEP_TIME: pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getStartTime()), TimeZone.getDefault()), num); break; case SEQUENCE_TIME: // pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getTestSequenceInstance().getStartTime()), RegularTimePeriod.DEFAULT_TIME_ZONE), num); pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getTestSequenceInstance().getCreateTime()), TimeZone.getDefault()), num); break; } } } dataset.addSeries(pop); } JFreeChart chart = null; switch (chartMode) { case STEP_TIME: chart = ChartFactory.createTimeSeriesChart(null, "Step Started Time", getValueString(), dataset, isGrouping(), true, false); break; case SEQUENCE_TIME: chart = ChartFactory.createTimeSeriesChart(null, "Sequence Started Time", getValueString(), dataset, isGrouping(), true, false); break; } chart.setBackgroundPaint((Paint) UIManager.get("Panel.background")); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.white); XYLineAndShapeRenderer renderer5 = new XYLineAndShapeRenderer(); renderer5.setBaseSeriesVisibleInLegend(false); plot.setRenderer(renderer5); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); plot.setRangeCrosshairVisible(true); plot.setDomainCrosshairVisible(true); // chart.setTitle(valueName); placeLimitMarkers(plot, true); //renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); renderer5.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance()); /* coloring */ if (isCategorization()) { // TreeMap<String, Color> cmap = new TreeMap<String, Color>(); int i = 0; for (Iterator<String> it = catstats.keySet().iterator(); it.hasNext(); i++) { String groupName = it.next(); Color c = ChartCategories.getColor(i); for (int j = 0; j < dataset.getSeriesCount(); j++) { TimeSeries ts = dataset.getSeries(j); if (ts.getKey().equals(groupName)) { renderer5.setSeriesPaint(j, c); } } } } else { renderer5.setSeriesPaint(0, ChartCategories.getColor(0)); } // chart.addProgressListener(new ChartProgressListener() { // // public void chartProgress(final ChartProgressEvent progress) { // SwingUtilities.invokeLater( // new Runnable() { // // @Override // public void run() { // // System.out.println("progress:" + progress + " " + progress.getType()); // if (progress.getType() == ChartProgressEvent.DRAWING_FINISHED) { // if (plot != null) { // if (plot.isDomainCrosshairVisible() && plot.isDomainCrosshairLockedOnData()) { //// System.out.println("getDomainCrosshairValue:" + plot.getDomainCrosshairValue()); // double xx = plot.getDomainCrosshairValue(); // if (xx != 0.0) { // long x = (long) xx; // System.out.println(new Date(x)); // for (TestStepInstance step : testStepInstances.getSteps()) { // if (step.getStartTime() != null && step.getStartTime().equals(x)) { // testStepInstances.selectStep(step); // } // } // System.out.println(new Date(x)); // } // } //// if (plot.isRangeCrosshairVisible()) { //// System.out.println("getRangeCrosshairValue:" + plot.getRangeCrosshairValue()); //// } // } // } // } // }); // } // }); // chart.addChangeListener(new ChartChangeListener() { // // public void chartChanged(ChartChangeEvent event) { // System.out.println("event:" + event); // if (event != null) { //// JFreeChart chart = event.getChart(); //// System.out.println("chart:" + chart); //// if (chart != null) { //// System.out.println("title:" + event.getChart().getTitle()); //// } // System.out.println("type:" + event.getType()); // if (plot != null) { // if (plot.isDomainCrosshairVisible()) { // System.out.println("getDomainCrosshairValue:" + plot.getDomainCrosshairValue()); // long x = (long) plot.getDomainCrosshairValue(); // for (TestStepInstance step : testStepInstances.getSteps()) { // if (step.getStartTime() != null && step.getStartTime().equals(x)) { // testStepInstances.selectStep(step); // } // } // System.out.println(new Date(x)); // } // if (plot.isRangeCrosshairVisible()) { // System.out.println("getRangeCrosshairValue:" + plot.getRangeCrosshairValue()); // } // } // } // } // }); chart.setTextAntiAlias(false); return chart; }
From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java
private boolean writeDetailedFactorAnalysis(ExpressionExperiment ee, OutputStream os) throws Exception { SVDValueObject svdo = svdService.getSvdFactorAnalysis(ee.getId()); if (svdo == null) return false; if (svdo.getFactors().isEmpty() && svdo.getDates().isEmpty()) { return false; }//w ww . java 2s. com Map<Integer, Map<Long, Double>> factorCorrelations = svdo.getFactorCorrelations(); // Map<Integer, Map<Long, Double>> factorPvalues = svdo.getFactorPvalues(); Map<Integer, Double> dateCorrelations = svdo.getDateCorrelations(); assert ee.getId().equals(svdo.getId()); ee = expressionExperimentService.thawLite(ee); // need the experimental design int maxWidth = 30; Map<Long, String> efs = this.getFactorNames(ee, maxWidth); Map<Long, ExperimentalFactor> efIdMap = EntityUtils .getIdMap(ee.getExperimentalDesign().getExperimentalFactors()); Collection<Long> continuousFactors = new HashSet<>(); for (ExperimentalFactor ef : ee.getExperimentalDesign().getExperimentalFactors()) { boolean isContinous = ExperimentalDesignUtils.isContinuous(ef); if (isContinous) { continuousFactors.add(ef.getId()); } } /* * Make plots of the dates vs. PCs, factors vs. PCs. */ int MAX_COMP = 3; Map<Long, List<JFreeChart>> charts = new LinkedHashMap<>(); ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme()); /* * FACTORS */ String componentShorthand = "PC"; for (Integer component : factorCorrelations.keySet()) { if (component >= MAX_COMP) break; String xaxisLabel = componentShorthand + (component + 1); for (Long efId : factorCorrelations.get(component).keySet()) { /* * Should not happen. */ if (!efs.containsKey(efId)) { log.warn("No experimental factor with id " + efId); continue; } if (!svdo.getFactors().containsKey(efId)) { // this should not happen. continue; } boolean isCategorical = !continuousFactors.contains(efId); Map<Long, String> categories = new HashMap<>(); if (isCategorical) { this.getCategories(efIdMap, efId, categories); } if (!charts.containsKey(efId)) { charts.put(efId, new ArrayList<JFreeChart>()); } Double a = factorCorrelations.get(component).get(efId); String plotname = (efs.get(efId) == null ? "?" : efs.get(efId)) + " " + xaxisLabel; // unique? if (a != null && !Double.isNaN(a)) { String title = plotname + " " + String.format("%.2f", a); List<Double> values = svdo.getFactors().get(efId); Double[] eigenGene = this.getEigenGene(svdo, component); assert values.size() == eigenGene.length; /* * Plot eigengene vs values, add correlation to the plot */ JFreeChart chart; if (isCategorical) { /* * Categorical factor */ // use the absolute value of the correlation, since direction is arbitrary. title = plotname + " " + String.format("r=%.2f", Math.abs(a)); DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); /* * What this code does is organize the factor values by the groups. */ Map<String, List<Double>> groupedValues = new TreeMap<>(); for (int i = 0; i < values.size(); i++) { Long fvId = values.get(i).longValue(); String fvValue = categories.get(fvId); if (fvValue == null) { /* * Problem ...eg gill2006fateinocean id=1748 -- missing values. We just don't plot * anything for this sample. */ continue; // is this all we need to do? } if (!groupedValues.containsKey(fvValue)) { groupedValues.put(fvValue, new ArrayList<Double>()); } groupedValues.get(fvValue).add(eigenGene[i]); if (log.isDebugEnabled()) log.debug(fvValue + " " + values.get(i)); } for (String key : groupedValues.keySet()) { dataset.add(groupedValues.get(key), plotname, key); } // don't show the name of the X axis: it's redundant with the title. NumberAxis rangeAxis = new NumberAxis(xaxisLabel); rangeAxis.setAutoRangeIncludesZero(false); // rangeAxis.setAutoRange( false ); rangeAxis.setAutoRangeMinimumSize(4.0); // rangeAxis.setRange( new Range( -2, 2 ) ); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis(null), rangeAxis, new ScatterRenderer()); plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); chart = new JFreeChart(title, new Font("SansSerif", Font.BOLD, 12), plot, false); ScatterRenderer renderer = (ScatterRenderer) plot.getRenderer(); float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesFillPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); renderer.setUseOutlinePaint(false); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(Color.white); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); } else { /* * Continuous value factor */ DefaultXYDataset series = new DefaultXYDataset(); series.addSeries(plotname, new double[][] { ArrayUtils.toPrimitive(values.toArray(new Double[] {})), ArrayUtils.toPrimitive(eigenGene) }); // don't show x-axis label, which would otherwise be efs.get( efId ) chart = ChartFactory.createScatterPlot(title, null, xaxisLabel, series, PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); XYItemRenderer renderer = plot.getRenderer(); renderer.setBasePaint(Color.white); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); plot.setRenderer(renderer); } chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); charts.get(efId).add(chart); } } } /* * DATES */ charts.put(-1L, new ArrayList<JFreeChart>()); for (Integer component : dateCorrelations.keySet()) { String xaxisLabel = componentShorthand + (component + 1); List<Date> dates = svdo.getDates(); if (dates.isEmpty()) break; long secspan = ubic.basecode.util.DateUtil.numberOfSecondsBetweenDates(dates); if (component >= MAX_COMP) break; Double a = dateCorrelations.get(component); if (a != null && !Double.isNaN(a)) { Double[] eigenGene = svdo.getvMatrix().getColObj(component); /* * Plot eigengene vs values, add correlation to the plot */ TimeSeries series = new TimeSeries("Dates vs. eigen" + (component + 1)); int i = 0; for (Date d : dates) { // if span is less than an hour, retain the minute. if (secspan < 60 * 60) { series.addOrUpdate(new Minute(d), eigenGene[i++]); } else { series.addOrUpdate(new Hour(d), eigenGene[i++]); } } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Dates: " + xaxisLabel + " " + String.format("r=%.2f", a), null, xaxisLabel, dataset, false, false, false); XYPlot xyPlot = chart.getXYPlot(); chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); // standard renderer makes lines. XYDotRenderer renderer = new XYDotRenderer(); renderer.setBaseFillPaint(Color.white); renderer.setDotHeight(3); renderer.setDotWidth(3); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); // has no effect, need dotheight. float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); ValueAxis domainAxis = xyPlot.getDomainAxis(); domainAxis.setVerticalTickLabels(true); xyPlot.setRenderer(renderer); xyPlot.setRangeGridlinesVisible(false); xyPlot.setDomainGridlinesVisible(false); charts.get(-1L).add(chart); } } /* * Plot in a grid, with each factor as a column. FIXME What if we have too many factors to fit on the screen? */ int columns = (int) Math.ceil(charts.size()); int perChartSize = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX; BufferedImage image = new BufferedImage(columns * perChartSize, MAX_COMP * perChartSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); int currentX = 0; int currentY = 0; for (Long id : charts.keySet()) { for (JFreeChart chart : charts.get(id)) { this.addChartToGraphics(chart, g2, currentX, currentY, perChartSize, perChartSize); if (currentY + perChartSize < MAX_COMP * perChartSize) { currentY += perChartSize; } else { currentY = 0; currentX += perChartSize; } } } os.write(ChartUtilities.encodeAsPNG(image)); return true; }
From source file:fmiquerytest.Coordinates.java
static String drawTempRainChart(List<stepWeather> stepDataBase, Map routeWeather) { //First, fetch the real data List<Double> times = new ArrayList<>(); List<Double> temps = new ArrayList<>(); List<Double> rains = new ArrayList<>(); List<Double> lights = new ArrayList<>(); for (int i = 0; i < stepDataBase.size(); ++i) { stepWeather step = stepDataBase.get(i); stepWeather nextstep = step;/*from w w w . j a v a2 s . c o m*/ if (i < stepDataBase.size() - 1) { nextstep = stepDataBase.get(i + 1); } times.add(step.timeAsDouble); temps.add(getParameterAverage(routeWeather, step, nextstep, "Temperature")); rains.add(getParameterAverage(routeWeather, step, nextstep, "Precipitation1h")); lights.add(Math.pow(Math.abs(step.timeAsDouble % 24 - ((step.sunRise + step.sunSet) / 2)) / ((step.sunSet - step.sunRise) / 2), 5)); } double zeroPoint = times.get(0); // Make first dataset final TimeSeriesCollection dataset = new TimeSeriesCollection(); final TimeSeries s1 = new TimeSeries("Temperature C", Minute.class); // Make second dataset final TimeSeriesCollection dataset2 = new TimeSeriesCollection(); final TimeSeries s2 = new TimeSeries("Rain (mm)", Minute.class); // Make third dataset //final TimeSeriesCollection dataset3 = new TimeSeriesCollection(); final TimeSeries s3 = new TimeSeries("Darkness", Minute.class); // Show data per minute RegularTimePeriod start = new Minute(new Date(FmiQueryTest.startTimeMillis)); for (int i = 0; i < times.size() - 1; ++i) { double time = times.get(i); double nexttime = times.get(i + 1); int firstMinute = intValue((time - zeroPoint) * 60); int currentMinute = firstMinute; int lastMinute = intValue((nexttime - zeroPoint) * 60); while (currentMinute < lastMinute) { s1.add(start, temps.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute) * (temps.get(i + 1) - temps.get(i))); s2.add(start, (rains.get(i) + rains.get(i + 1)) / 2); //+((double)currentMinute-firstMinute)/(lastMinute-firstMinute)*(rains.get(i+1)-rains.get(i))); s3.add(start, lights.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute) * (lights.get(i + 1) - lights.get(i))); ++currentMinute; start = start.next(); } } dataset.addSeries(s1); dataset2.addSeries(s3); dataset2.addSeries(s2); // Initialize chart final JFreeChart chart = ChartFactory.createTimeSeriesChart("Temperature and rain", "Time", "Temperature C", dataset, true, // legend? true, // tooltips? false // URLs? ); final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLowerMargin(0.0); plot.getDomainAxis().setUpperMargin(0.0); // configure the range axis to display first dataset... final ValueAxis rangeAxis = (ValueAxis) plot.getRangeAxis(); rangeAxis.setRange(-30, 30); final TickUnits units = new TickUnits(); units.add(new NumberTickUnit(10.0)); units.add(new NumberTickUnit(1.0)); units.add(new NumberTickUnit(0.1)); rangeAxis.setStandardTickUnits(units); //rangeAxis.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16)); // add the secondary dataset/renderer/axis plot.setRangeAxis(rangeAxis); final XYItemRenderer renderer2 = new XYAreaRenderer(); final ValueAxis axis2 = new NumberAxis("Rain (mm) "); axis2.setRange(0, 2); axis2.setStandardTickUnits(units); //axis2.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16)); renderer2.setSeriesPaint(0, new Color(0, 0, 255, 128)); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); final XYItemRenderer renderer3 = new XYAreaRenderer(); renderer3.setSeriesPaint(0, new Color(0, 0, 0, 64)); //plot.setDataset(1, dataset2); plot.setRenderer(1, renderer3); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); chart.setBackgroundPaint(Color.white); //plot.setBackgroundPaint(Color.lightGray); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.black); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.black); // final TextTitle subtitle = new TextTitle("An area chart demonstration. We use this " // + "subtitle as an example of what happens when you get a really long title or " // + "subtitle."); // subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12)); // subtitle.setPosition(RectangleEdge.TOP); //// subtitle.setSpacer(new Spacer(Spacer.RELATIVE, 0.05, 0.05, 0.05, 0.05)); // subtitle.setVerticalAlignment(VerticalAlignment.BOTTOM); // chart.addSubtitle(subtitle); // Produce chart // ChartFrame frame = new ChartFrame("Tamperature and rain", chart); // frame.pack(); // RefineryUtilities.centerFrameOnScreen(frame); // frame.setVisible(true); ByteArrayOutputStream bas = new ByteArrayOutputStream(); try { ChartUtilities.writeChartAsPNG(bas, chart, 600, 400); } catch (IOException ex) { Logger.getLogger(WeatherTools.class.getName()).log(Level.SEVERE, null, ex); } byte[] byteArray = bas.toByteArray(); String baseCode = Base64.encode(byteArray); return "<img width=\"480\" alt=\"Temperature and rain\" src=\"data:image/png;base64," + baseCode.trim() + "\" />"; }
From source file:ro.nextreports.engine.chart.JFreeChartExporter.java
private JFreeChart createLineChart() throws QueryException { XYSeriesCollection dataset = new XYSeriesCollection(); String chartTitle = replaceParameters(chart.getTitle().getTitle()); chartTitle = StringUtil.getI18nString(chartTitle, I18nUtil.getLanguageByName(chart, language)); Object[] charts = new Object[chart.getYColumns().size()]; List<String> legends = chart.getYColumnsLegends(); boolean hasLegend = false; for (int i = 0; i < charts.length; i++) { String legend = ""; try {//from www. jav a 2s. c o m legend = replaceParameters(legends.get(i)); legend = StringUtil.getI18nString(legend, I18nUtil.getLanguageByName(chart, language)); } catch (IndexOutOfBoundsException ex) { // no legend set } if ((legend != null) && !"".equals(legend.trim())) { hasLegend = true; } XYSeries lineChart = new XYSeries(legend); charts[i] = lineChart; dataset.addSeries(lineChart); } String xLegend = StringUtil.getI18nString(replaceParameters(chart.getXLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); String yLegend = StringUtil.getI18nString(replaceParameters(chart.getYLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); JFreeChart jfreechart = ChartFactory.createXYLineChart(chartTitle, // Title replaceParameters(xLegend), // x-axis Label replaceParameters(yLegend), // y-axis Label dataset, // Dataset PlotOrientation.VERTICAL, // Plot Orientation true, // Show Legend true, // Use tooltips false // Configure chart to generate URLs? ); // hide legend if necessary if (!hasLegend) { jfreechart.removeLegend(); } // hide border jfreechart.setBorderVisible(false); // title setTitle(jfreechart); // charts colors & values boolean showValues = (chart.getShowYValuesOnChart() == null) ? false : chart.getShowYValuesOnChart(); DecimalFormat decimalFormat; DecimalFormat percentageFormat; if (chart.getYTooltipPattern() == null) { decimalFormat = new DecimalFormat("#"); percentageFormat = new DecimalFormat("0.00%"); } else { decimalFormat = new DecimalFormat(chart.getYTooltipPattern()); percentageFormat = decimalFormat; } XYPlot plot = (XYPlot) jfreechart.getPlot(); for (int i = 0; i < charts.length; i++) { plot.getRenderer().setSeriesPaint(i, chart.getForegrounds().get(i)); if (showValues) { plot.getRenderer().setSeriesItemLabelsVisible(i, true); plot.getRenderer().setSeriesItemLabelGenerator(i, new StandardXYItemLabelGenerator("{2}", decimalFormat, percentageFormat)); } } if (showValues) { // increase a little bit the range axis to view all item label values over points plot.getRangeAxis().setUpperMargin(0.2); } // grid axis visibility & colors if ((chart.getXShowGrid() != null) && !chart.getXShowGrid()) { plot.setDomainGridlinesVisible(false); } else { if (chart.getXGridColor() != null) { plot.setDomainGridlinePaint(chart.getXGridColor()); } else { plot.setDomainGridlinePaint(Color.BLACK); } } if ((chart.getYShowGrid() != null) && !chart.getYShowGrid()) { plot.setRangeGridlinesVisible(false); } else { if (chart.getYGridColor() != null) { plot.setRangeGridlinePaint(chart.getYGridColor()); } else { plot.setRangeGridlinePaint(Color.BLACK); } } // chart background plot.setBackgroundPaint(chart.getBackground()); // labels color plot.getDomainAxis().setTickLabelPaint(chart.getXColor()); plot.getRangeAxis().setTickLabelPaint(chart.getYColor()); //legend color plot.getDomainAxis().setLabelPaint(chart.getXLegend().getColor()); plot.getRangeAxis().setLabelPaint(chart.getYLegend().getColor()); // legend font plot.getDomainAxis().setLabelFont(chart.getXLegend().getFont()); plot.getRangeAxis().setLabelFont(chart.getYLegend().getFont()); // hide labels if ((chart.getXShowLabel() != null) && !chart.getXShowLabel()) { plot.getDomainAxis().setTickLabelsVisible(false); plot.getDomainAxis().setTickMarksVisible(false); } if ((chart.getYShowLabel() != null) && !chart.getYShowLabel()) { plot.getRangeAxis().setTickLabelsVisible(false); plot.getRangeAxis().setTickMarksVisible(false); } // label orientation if (chart.getXorientation() == Chart.VERTICAL) { plot.getDomainAxis().setVerticalTickLabels(true); } // labels fonts plot.getDomainAxis().setTickLabelFont(chart.getXLabelFont()); plot.getRangeAxis().setTickLabelFont(chart.getYLabelFont()); // point style Shape pointShape = null; byte style = chart.getType().getStyle(); switch (style) { case ChartType.STYLE_LINE_DOT_SOLID: case ChartType.STYLE_LINE_DOT_HOLLOW: pointShape = new Ellipse2D.Float(-3.0f, -3.0f, 6.0f, 6.0f); break; case ChartType.STYLE_LINE_DOT_ANCHOR: // triangle GeneralPath s5 = new GeneralPath(); s5.moveTo(0.0f, -3.0f); s5.lineTo(3.0f, 3.0f); s5.lineTo(-3.0f, 3.0f); s5.closePath(); pointShape = s5; break; case ChartType.STYLE_LINE_DOT_BOW: GeneralPath s4 = new GeneralPath(); s4.moveTo(-3.0f, -3.0f); s4.lineTo(3.0f, -3.0f); s4.lineTo(-3.0f, 3.0f); s4.lineTo(3.0f, 3.0f); s4.closePath(); pointShape = s4; break; case ChartType.STYLE_LINE_DOT_STAR: pointShape = new Star(-3.0f, 0f).getShape(); break; default: // no shape break; } if (pointShape != null) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setUseFillPaint(true); for (int i = 0; i < charts.length; i++) { renderer.setSeriesShapesVisible(i, true); if (style != ChartType.STYLE_LINE_DOT_SOLID) { renderer.setSeriesFillPaint(i, chart.getBackground()); } else { renderer.setSeriesFillPaint(i, chart.getForegrounds().get(i)); } renderer.setSeriesShape(i, pointShape); } } final HashMap<String, String> formatValues = createChart(plot.getRangeAxis(), charts); // in x axis does not contain number values , values are strings representing one unit if (!integerXValue) { ((NumberAxis) plot.getDomainAxis()).setTickUnit(new NumberTickUnit(1)); ((NumberAxis) plot.getDomainAxis()).setNumberFormatOverride(new DecimalFormat() { @Override public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { String s = formatValues.get(String.valueOf(Math.round(number))); if (s == null) { s = ""; } return result.append(s); } }); } return jfreechart; }
From source file:ro.nextreports.engine.chart.JFreeChartExporter.java
private JFreeChart createBubbleChart() throws QueryException { bubbleDataset = new DefaultXYZDataset(); // x, y are inverted for jfree bubble chart! // that's why we use minX & maxX values to compute Tu (tickUnit) String chartTitle = replaceParameters(chart.getTitle().getTitle()); chartTitle = StringUtil.getI18nString(chartTitle, I18nUtil.getLanguageByName(chart, language)); String xLegend = StringUtil.getI18nString(replaceParameters(chart.getYLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); String yLegend = StringUtil.getI18nString(replaceParameters(chart.getXLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); JFreeChart jfreechart = ChartFactory.createBubbleChart(chartTitle, xLegend, // x-axis Label yLegend, // y-axis Label bubbleDataset, PlotOrientation.HORIZONTAL, true, true, false); // hide border jfreechart.setBorderVisible(false);/*from ww w . ja va2 s .co m*/ // title setTitle(jfreechart); boolean showValues = (chart.getShowYValuesOnChart() == null) ? false : chart.getShowYValuesOnChart(); XYPlot xyplot = (XYPlot) jfreechart.getPlot(); xyplot.setForegroundAlpha(transparency); XYItemRenderer xyitemrenderer = xyplot.getRenderer(); DecimalFormat decimalformat; DecimalFormat percentageFormat; if (chart.getYTooltipPattern() == null) { decimalformat = new DecimalFormat("#"); percentageFormat = new DecimalFormat("0.00%"); } else { decimalformat = new DecimalFormat(chart.getYTooltipPattern()); percentageFormat = decimalformat; } if (showValues) { // increase a little bit the range axis to view all item label values over bars xyplot.getRangeAxis().setUpperMargin(0.2); } // grid axis visibility & colors if ((chart.getXShowGrid() != null) && !chart.getXShowGrid()) { xyplot.setDomainGridlinesVisible(false); } else { if (chart.getXGridColor() != null) { xyplot.setDomainGridlinePaint(chart.getXGridColor()); } else { xyplot.setDomainGridlinePaint(Color.BLACK); } } if ((chart.getYShowGrid() != null) && !chart.getYShowGrid()) { xyplot.setRangeGridlinesVisible(false); } else { if (chart.getYGridColor() != null) { xyplot.setRangeGridlinePaint(chart.getYGridColor()); } else { xyplot.setRangeGridlinePaint(Color.BLACK); } } // chart background xyplot.setBackgroundPaint(chart.getBackground()); // labels color xyplot.getDomainAxis().setTickLabelPaint(chart.getXColor()); xyplot.getRangeAxis().setTickLabelPaint(chart.getYColor()); // legend color xyplot.getDomainAxis().setLabelPaint(chart.getXLegend().getColor()); xyplot.getRangeAxis().setLabelPaint(chart.getYLegend().getColor()); // legend font xyplot.getDomainAxis().setLabelFont(chart.getXLegend().getFont()); xyplot.getRangeAxis().setLabelFont(chart.getYLegend().getFont()); // axis color xyplot.getDomainAxis().setAxisLinePaint(chart.getxAxisColor()); xyplot.getRangeAxis().setAxisLinePaint(chart.getyAxisColor()); // hide labels if ((chart.getXShowLabel() != null) && !chart.getXShowLabel()) { xyplot.getDomainAxis().setTickLabelsVisible(false); xyplot.getDomainAxis().setTickMarksVisible(false); } if ((chart.getYShowLabel() != null) && !chart.getYShowLabel()) { xyplot.getRangeAxis().setTickLabelsVisible(false); xyplot.getRangeAxis().setTickMarksVisible(false); } // label orientation ValueAxis domainAxis = xyplot.getDomainAxis(); if (chart.getXorientation() == Chart.VERTICAL) { domainAxis.setLabelAngle(Math.PI / 2); } else if (chart.getXorientation() == Chart.DIAGONAL) { domainAxis.setLabelAngle(Math.PI / 4); } else if (chart.getXorientation() == Chart.HALF_DIAGONAL) { domainAxis.setLabelAngle(Math.PI / 8); } // labels fonts xyplot.getDomainAxis().setTickLabelFont(chart.getXLabelFont()); xyplot.getRangeAxis().setTickLabelFont(chart.getYLabelFont()); createChart(xyplot.getRangeAxis(), new Object[4]); double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double maxZ = Double.MIN_VALUE; for (String serie : bubbleData.keySet()) { XYZList xyzList = bubbleData.get(serie); List<Number> yList = xyzList.getyList(); for (Number n : yList) { minY = Math.min(minY, n.doubleValue()); maxY = Math.max(maxY, n.doubleValue()); } List<Number> xList = xyzList.getxList(); for (Number n : xList) { minX = Math.min(minX, n.doubleValue()); maxX = Math.max(maxX, n.doubleValue()); } List<Number> zList = xyzList.getzList(); for (Number n : zList) { maxZ = Math.max(maxZ, n.doubleValue()); } } double tu = Math.floor((maxX - minX) / 5 + 0.5d); NumberTickUnit rUnit = new NumberTickUnit(tu); ((NumberAxis) xyplot.getRangeAxis()).setTickUnit(rUnit); // make the bubble with text fit on X axis (which is shown vertically!) xyplot.getDomainAxis().setUpperMargin(0.2); xyplot.getDomainAxis().setLowerMargin(0.2); for (String serie : bubbleData.keySet()) { XYZList xyzList = bubbleData.get(serie); double[][] data = { getDoubleArray(xyzList.getyList()), getDoubleArray(xyzList.getxList()), getZDoubleArray(xyzList.getzList(), tu, maxZ) }; bubbleDataset.addSeries(serie, data); } int series = bubbleData.keySet().size(); for (int i = 0; i < series; i++) { xyitemrenderer.setSeriesPaint(i, chart.getForegrounds().get(i)); if (showValues) { xyitemrenderer.setSeriesItemLabelsVisible(i, true); xyitemrenderer.setSeriesItemLabelGenerator(i, new StandardXYItemLabelGenerator("{2}", decimalformat, percentageFormat)); } } // show labels on bubbles xyitemrenderer.setBaseItemLabelsVisible(true); xyitemrenderer.setBaseItemLabelGenerator(new LegendXYItemLabelGenerator()); return jfreechart; }
From source file:org.operamasks.faces.render.graph.ChartRenderer.java
protected void setChartAxes(JFreeChart chart, UIChart comp) { UIAxis xAxis = comp.getxAxis();// w ww . j ava2s. c o m UIAxis yAxis = comp.getyAxis(); String xAxisLabel = comp.getxAxisLabel(); String yAxisLabel = comp.getyAxisLabel(); Plot plot = chart.getPlot(); Axis domainAxis = null; Axis rangeAxis = null; if (plot instanceof CategoryPlot) { CategoryPlot categoryPlot = (CategoryPlot) plot; if (yAxis != null && yAxis.isLogarithmic()) categoryPlot.setRangeAxis(new LogarithmicAxis(null)); domainAxis = categoryPlot.getDomainAxis(); rangeAxis = categoryPlot.getRangeAxis(); if (xAxis != null) { Boolean drawGridLine = xAxis.getDrawGridLine(); if (drawGridLine != null) { categoryPlot.setDomainGridlinesVisible(drawGridLine); } Paint gridLineColor = xAxis.getGridLineColor(); if (gridLineColor != null) { categoryPlot.setDomainGridlinePaint(gridLineColor); } } if (yAxis != null) { Boolean drawGridLine = yAxis.getDrawGridLine(); if (drawGridLine != null) { categoryPlot.setRangeGridlinesVisible(drawGridLine); } Paint gridLineColor = yAxis.getGridLineColor(); if (gridLineColor != null) { categoryPlot.setRangeGridlinePaint(gridLineColor); } } } else if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; if (xAxis != null && xAxis.isLogarithmic()) xyPlot.setDomainAxis(new LogarithmicAxis(null)); if (yAxis != null && yAxis.isLogarithmic()) xyPlot.setRangeAxis(new LogarithmicAxis(null)); domainAxis = xyPlot.getDomainAxis(); rangeAxis = xyPlot.getRangeAxis(); if (xAxis != null) { Boolean drawGridLine = xAxis.getDrawGridLine(); if (drawGridLine != null) { xyPlot.setDomainGridlinesVisible(drawGridLine); } Paint gridLineColor = xAxis.getGridLineColor(); if (gridLineColor != null) { xyPlot.setDomainGridlinePaint(gridLineColor); } Boolean drawBaseLine = xAxis.getDrawBaseLine(); if (drawBaseLine != null) { xyPlot.setDomainZeroBaselineVisible(drawBaseLine); } Paint baseLineColor = xAxis.getBaseLineColor(); if (baseLineColor != null) { xyPlot.setDomainZeroBaselinePaint(baseLineColor); } } if (yAxis != null) { Boolean drawGridLine = yAxis.getDrawGridLine(); if (drawGridLine != null) { xyPlot.setRangeGridlinesVisible(drawGridLine); } Paint gridLineColor = yAxis.getGridLineColor(); if (gridLineColor != null) { xyPlot.setRangeGridlinePaint(gridLineColor); } Boolean drawBaseLine = yAxis.getDrawBaseLine(); if (drawBaseLine != null) { xyPlot.setRangeZeroBaselineVisible(drawBaseLine); } Paint baseLineColor = yAxis.getBaseLineColor(); if (baseLineColor != null) { xyPlot.setRangeZeroBaselinePaint(baseLineColor); } } } if (domainAxis != null) { if (xAxisLabel != null) domainAxis.setLabel(xAxisLabel); if (xAxis != null) setAxisStyles(domainAxis, xAxis); } if (rangeAxis != null) { if (yAxisLabel != null) rangeAxis.setLabel(yAxisLabel); if (yAxis != null) setAxisStyles(rangeAxis, yAxis); } }
From source file:edu.fullerton.viewerplugin.TsPlot.java
@Override public ArrayList<Integer> makePlot(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException { int imageId;// w w w. j a v a 2 s. c o m try { if (parameterMap.containsKey("ts_newplt")) { imageId = makeAddPlotFiles(dbufs, compact); } else { String gtitle = getTitle(dbufs, compact); XYSeriesCollection xyds = new XYSeriesCollection(); TimeSeriesCollection mtds = new TimeSeriesCollection(); compact = dbufs.size() > 2 ? false : compact; for (ChanDataBuffer dbuf : dbufs) { if (timeAxis.equalsIgnoreCase("utc")) { addTimeSeries(dbuf, compact, mtds); } else { addXySeries(dbuf, compact, xyds); } } Double minx, miny, maxx, maxy; Double[] rng = new Double[4]; if (timeAxis.equalsIgnoreCase("utc")) { PluginSupport.getRangeLimits(mtds, rng); } else { PluginSupport.getRangeLimits(xyds, rng, 0); } minx = rng[0]; miny = rng[1]; maxx = rng[2]; maxy = rng[3]; int exp; if (timeAxis.equalsIgnoreCase("utc")) { exp = PluginSupport.scaleRange(mtds, miny, maxy); } else { exp = PluginSupport.scaleRange(xyds, miny, maxy); } ChartPanel cpnl; DefaultXYDataset ds = new DefaultXYDataset(); JFreeChart chart; if (timeAxis.equalsIgnoreCase("utc")) { chart = ChartFactory.createTimeSeriesChart(gtitle, "Time (UTC)", "Amplitude (Counts)", ds, true, true, false); } else { chart = ChartFactory.createXYLineChart(gtitle, xAxisLabel, "Amplitude (Counts)", ds, PlotOrientation.VERTICAL, true, false, false); } XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis rangeAxis = new NumberAxis("Amplitude (Counts)"); ScaledAxisNumberFormat sanf = new ScaledAxisNumberFormat(); sanf.setExp(exp); if (maxy != 0 && Math.abs(maxy - miny) <= Math.abs(maxy) * 1e-25) { // this garbage is to get jFreeChart to put labels on the Y axis double dt = Math.abs(miny) / 10; double scaledMin = (miny - dt) * Math.pow(10., exp); double scaledMax = (maxy + dt) * Math.pow(10., exp); rangeAxis.setRange(scaledMin, scaledMax); NumberTickUnit unit = new NumberTickUnit((scaledMax - scaledMin) / 10.); rangeAxis.setTickUnit(unit); rangeAxis.setAutoRange(false); } // else // { // sanf.setMinMax(miny, maxy); // rangeAxis.setRange(miny, maxy); // NumberTickUnit unit = new NumberTickUnit((maxy - miny)/6.); // rangeAxis.setTickUnit(unit); // rangeAxis.setAutoRange(false); // } rangeAxis.setNumberFormatOverride(sanf); rangeAxis.setAutoRangeIncludesZero(false); plot.setRangeAxis(rangeAxis); if (timeAxis.equalsIgnoreCase("utc")) { plot.setDataset(0, mtds); } else { plot.setDataset(0, xyds); } // Set the line thickness XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer(); BasicStroke str = new BasicStroke(lineThickness); int n = plot.getSeriesCount(); for (int i = 0; i < n; i++) { r.setSeriesStroke(i, str); } plot.setBackgroundPaint(Color.WHITE); // add plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.BLACK); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.BLACK); r.setBaseFillPaint(Color.WHITE); if (compact) { chart.removeLegend(); } chart.setBackgroundPaint(Color.WHITE); cpnl = new ChartPanel(chart); imageId = saveImageAsPNG(cpnl); } } catch (LdvTableException | NoSuchAlgorithmException | SQLException | IOException ex) { throw new WebUtilException("Making time series plot: ", ex); } ArrayList<Integer> ret = new ArrayList<Integer>(); ret.add(imageId); return ret; }
From source file:org.fhcrc.cpl.viewer.gui.MRMDialog.java
/** * Draw a chart in a panel. Good for precursors and daughters * @param parentPanel//from ww w . j a va 2s .c o m * @param dataset * @param domainMin * @param domainMax * @param supplier * @param wg */ protected void createChartInPanel(JPanel parentPanel, XYSeriesCollection dataset, Double domainMin, Double domainMax, DrawingSupplier supplier, whichGraph wg) { if (precursorChromatogramEmpty(transitionOnPlot) && wg == whichGraph.Precursor) { precursorContainerContainerPanel.setVisible(false); if (this.getWidth() >= 100 && this.getHeight() >= 100) this.setPreferredSize(new Dimension(this.getWidth(), this.getHeight())); pack(); return; } switch (wg) { case Precursor: clearPreviousChartJunk(oldPrecursorChart); oldPrecursorChart = null; break; case Daughter: clearPreviousChartJunk(oldProductChart); oldProductChart = null; break; } JFreeChart chart = ChartFactory.createXYLineChart(null, "seconds", null, dataset, PlotOrientation.VERTICAL, true, false, false); chart.setBackgroundPaint(new Color(220, 220, 220)); XYPlot xyp = (XYPlot) (chart.getPlot()); xyp.setBackgroundPaint(Color.WHITE); xyp.setDomainGridlinesVisible(true); xyp.setRangeGridlinesVisible(true); xyp.setDomainGridlinePaint(Color.LIGHT_GRAY); xyp.setRangeGridlinePaint(Color.LIGHT_GRAY); if (supplier != null) { xyp.setDrawingSupplier(supplier); } else { xyp.setDrawingSupplier(Utils.plainDrawingSupplier(Color.LIGHT_GRAY)); } xyp.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE); CenterZoomNumberAxis axisDomain = new CenterZoomNumberAxis("seconds"); axisDomain.setAutoRangeIncludesZero(false); axisDomain.setRange(Math.max(0.0, domainMin), domainMax); axisDomain.addChangeListener(new domainAxisZoomCoordinator(axisDomain)); xyp.clearAnnotations(); xyp.setDomainAxis(axisDomain); xyp.getDomainAxis().setAutoRange(false); xyp.getRangeAxis().setAutoRange(false); XYLineAndShapeRenderer xylsr = (XYLineAndShapeRenderer) xyp.getRenderer(); xylsr.setLegendLine(Utils.legendThing(16, 6)); xylsr.setShapesFilled(true); xylsr.setBaseShapesFilled(true); PanelWithChart panelWithChart = new PanelWithChart(chart); ChartPanel cp = panelWithChart.getChartPanel(); cp.removeMouseListener(cp); cp.removeMouseMotionListener(cp); if (peaksTable != null) { MRMerMouseListener mml = new MRMerMouseListener(cp, (PeaksTableModel) peaksTable.getModel()); cp.addMouseListener(mml); cp.addMouseMotionListener(mml); } cp.setPreferredSize(new Dimension(parentPanel.getWidth(), parentPanel.getHeight() - 10)); cp.setDomainZoomable(true); cp.setRangeZoomable(false); cp.setPopupMenu(null); parentPanel.removeAll(); parentPanel.add(panelWithChart); switch (wg) { case Precursor: createChartInPanelPrecursorTasksOnly(xyp); oldPrecursorChart = xyp; break; case Daughter: createChartInPanelDaughterTasksOnly(xyp); oldProductChart = xyp; break; } parentPanel.updateUI(); listTransition.requestFocus(); }
From source file:com.appnativa.rare.ui.chart.jfreechart.ChartHandler.java
protected void customizeXYPlot(ChartPanel chartPanel, ChartDefinition cd, XYPlot plot) { PlotInformation pi = cd.getPlotInformation(); customizeBasicPlot(plot, pi);// w w w . j a v a 2s .c o m plot.clearRangeMarkers(); plot.clearDomainMarkers(); PlotOrientation po = cd.isVertical() ? PlotOrientation.VERTICAL : PlotOrientation.HORIZONTAL; plot.setOrientation(po); boolean showGrid = (pi == null) ? true : pi.isShowGridLines(); if (showGrid) { Color c = getGridColor(pi); UIStroke stroke = getGridStroke(pi); plot.setRangeGridlinePaint(c); plot.setDomainGridlinePaint(c); Stroke s = SwingHelper.getStroke(stroke); plot.setRangeGridlineStroke(s); plot.setDomainGridlineStroke(s); } else { plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); } if (pi != null) { Color c = pi.getBorderColor(); if (c != null) { plot.setOutlinePaint(c); } } int angle = cd.getDomainAxis().getAngle(); if ((angle != 0) && (angle != 180)) { plot.getDomainAxis().setLabelAngle(((angle) / 180f) * Math.PI); } else { plot.getDomainAxis().setLabelAngle(0); } angle = cd.getRangeAxis().getAngle(); if ((angle > 0) && (angle != 180)) { plot.getRangeAxis().setLabelAngle(((angle) / 180f) * Math.PI); } else { plot.getRangeAxis().setLabelAngle(0); } updateMarkers(cd, plot, true); updateMarkers(cd, plot, false); customizeXYLineAndShapeRenderer(cd, plot, pi); customizeSeriesAttributes(chartPanel, cd, plot, plot.getDatasetCount() > 1); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); }