List of usage examples for org.jfree.chart ChartFactory createTimeSeriesChart
public static JFreeChart createTimeSeriesChart(String title, String timeAxisLabel, String valueAxisLabel, XYDataset dataset, boolean legend, boolean tooltips, boolean urls)
From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.MeasurementGraphAction2.java
JFreeChart actualLabChartRefPlusMeds(String demographicNo, String labType, String identifier, String testName, String patientName, String chartTitle, String[] drugs) { org.jfree.data.time.TimeSeriesCollection dataset = new org.jfree.data.time.TimeSeriesCollection(); ArrayList<Map<String, Serializable>> list = null; MiscUtils.getLogger().debug(/*from w w w. j a v a2 s .c o m*/ " lab type >" + labType + "< >" + labType.equals("loinc") + "<" + testName + " " + identifier); if (labType.equals("loinc")) { try { Connection conn = DbConnectionFilter.getThreadLocalDbConnection(); list = CommonLabTestValues.findValuesByLoinc2(demographicNo, identifier, conn); MiscUtils.getLogger().debug("List ->" + list.size()); conn.close(); } catch (Exception ed) { MiscUtils.getLogger().error("Error", ed); } } else { list = CommonLabTestValues.findValuesForTest(labType, demographicNo, testName, identifier); } String typeYAxisName = ""; ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>(); String typeLegendName = "Lab Value"; typeYAxisName = "type Y"; boolean nameSet = false; TimeSeries newSeries = new TimeSeries(typeLegendName, Day.class); for (Map mdb : list) { if (!nameSet) { typeYAxisName = (String) mdb.get("units"); typeLegendName = (String) mdb.get("testName"); if (typeLegendName == null) { typeLegendName = testName; } newSeries.setKey(typeLegendName); nameSet = true; } newSeries.addOrUpdate(new Day((Date) mdb.get("collDateDate")), Double.parseDouble("" + mdb.get("result"))); log.debug("RANGE " + mdb.get("range")); if (mdb.get("range") != null) { String range = (String) mdb.get("range"); if (range.indexOf("-") != -1) { String[] sp = range.split("-"); double open = Double.parseDouble(sp[0]); double high = Double.parseDouble(sp[1]); double low = Double.parseDouble(sp[0]); double close = Double.parseDouble(sp[1]); double volume = 1045; dataItems.add(new OHLCDataItem(new Day((Date) mdb.get("collDateDate")).getStart(), open, high, low, close, volume)); } } } dataset.addSeries(newSeries); JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, "Days", typeYAxisName, dataset, true, true, true); XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setAutoRange(true); log.debug("LEN " + plot.getDomainAxis().getLowerBound() + " ddd " + plot.getDomainAxis().getUpperMargin() + " eee " + plot.getDomainAxis().getLowerMargin()); plot.getDomainAxis().setUpperMargin(plot.getDomainAxis().getUpperMargin() * 6); plot.getDomainAxis().setLowerMargin(plot.getDomainAxis().getLowerMargin() * 6); plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 1.7); plot.getDomainAxis().setUpperMargin(0.9); plot.getDomainAxis().setLowerMargin(0.9); plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 4); ValueAxis va = plot.getRangeAxis(); va.setAutoRange(true); XYItemRenderer renderer = plot.getRenderer(); //DateFormat.getInstance() XYItemLabelGenerator generator = new StandardXYItemLabelGenerator("{1} \n {2}", new SimpleDateFormat("yyyy.MM.dd"), new DecimalFormat("0.00")); renderer.setSeriesItemLabelGenerator(0, generator);//setLabelGenerator(generator); renderer.setBaseItemLabelsVisible(true); plot.setBackgroundPaint(Color.WHITE); plot.setDomainCrosshairPaint(Color.GRAY); if (renderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) renderer; rend.setBaseShapesVisible(true); rend.setBaseShapesFilled(true); } plot.setRenderer(renderer); if (dataItems != null && dataItems.size() > 0) { OHLCDataItem[] ohlc = dataItems.toArray(new OHLCDataItem[dataItems.size()]); XYDataset referenceRangeDataset = new DefaultOHLCDataset("Normal Reference Range", ohlc); plot.setDataset(1, referenceRangeDataset); plot.mapDatasetToRangeAxis(1, 0); plot.setRenderer(1, new HighLowRenderer()); } XYTaskDataset drugDataset = getDrugDataSet(demographicNo, drugs); //DateAxis xAxis = new DateAxis("Date/Time"); //DateAxis xAxis = plot.getRangeAxis(); SymbolAxis yAxis = new SymbolAxis("Meds", getDrugSymbol(demographicNo, drugs)); yAxis.setGridBandsVisible(false); XYBarRenderer xyrenderer = new XYBarRenderer(); xyrenderer.setUseYInterval(true); xyrenderer.setBarPainter(new StandardXYBarPainter()); //XYPlot xyplot = new XYPlot(drugDataset, xAxis, yAxis, xyrenderer); XYPlot xyplot = new XYPlot(drugDataset, plot.getDomainAxis(), yAxis, xyrenderer); xyplot.getDomainAxis().setUpperMargin(0.9); xyplot.getDomainAxis().setLowerMargin(0.9); CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(new DateAxis("Date/Time")); cplot.add(plot); cplot.add(xyplot); /////// chart = new JFreeChart(chartTitle, cplot); chart.setBackgroundPaint(Color.white); return chart; }
From source file:net.liuxuan.device.w3330.JIF_DrawChart_w3330.java
/** * ?jfreechart//w w w. ja va 2 s . co m */ public void initChart() { ts_wppm = new TimeSeries("PPM", Millisecond.class); ts_wppm_zero = new TimeSeries("PPM-Zero", Millisecond.class); ts_flux = new TimeSeries("Flux", Millisecond.class); ts_wvtr = new TimeSeries("WVTR", Millisecond.class); ts_tempcell = new TimeSeries(" Cell Temperature", Millisecond.class); ts_tempambi = new TimeSeries("Ambient Temperature", Millisecond.class); ts_status = new TimeSeries("Status", Millisecond.class); ts_fitting = new TimeSeries("fitting curve1", Millisecond.class); ts_fitting2 = new TimeSeries("fitting curve2", Millisecond.class); trcollection = new TimeSeriesCollection(ts_wppm); trcollection.addSeries(ts_wppm_zero); trcollection.addSeries(ts_wvtr); trcollection.addSeries(ts_fitting2);//ppm trcollection2 = new TimeSeriesCollection(ts_flux); trcollection2.addSeries(ts_fitting);//temp3 trcollection2.addSeries(ts_tempcell); trcollection2.addSeries(ts_tempambi); trcollection2.addSeries(ts_status); // timeseriescopylist.add(getTimeSeries(3).createCopy(0, getTimeSeries(3).getItemCount() - 1)); JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("", "Time(s)", "PPM", trcollection, true, true, false); XYPlot xyplot = jfreechart.getXYPlot(); xyplot.setDomainCrosshairVisible(true); xyplot.setRangeCrosshairVisible(true); Font fs = new Font("", Font.BOLD, 14); Font fs2 = new Font("", Font.BOLD, 12); XYLineAndShapeRenderer line0render = (XYLineAndShapeRenderer) xyplot.getRenderer(0); Color purple = new Color(139, 0, 255); line0render.setSeriesPaint(0, Color.blue); line0render.setSeriesPaint(1, Color.green); line0render.setSeriesPaint(2, Color.red); line0render.setSeriesPaint(3, purple); // line0render.setSeriesPaint(3, Color.ORANGE); XYLineAndShapeRenderer line1render = new XYLineAndShapeRenderer(); Color Rosered = new Color(230, 28, 100); line1render.setSeriesPaint(0, Color.orange); line1render.setSeriesPaint(1, Color.yellow); line1render.setSeriesPaint(2, Color.cyan); line1render.setSeriesPaint(3, Rosered); line1render.setBaseShapesVisible(false); xyplot.setRenderer(1, line1render); //?? ValueAxis valueaxis = xyplot.getDomainAxis(); // valueaxis.setLabelFont(fs); // valueaxis.setTickLabelFont(fs2); ValueAxis valueaxis2 = new NumberAxis(""); valueaxis2.setLabelFont(fs); valueaxis2.setTickLabelFont(fs2); xyplot.setRangeAxis(1, valueaxis2); xyplot.setDataset(1, trcollection2); xyplot.mapDatasetToRangeAxis(1, 1); //?? valueaxis.setAutoRange(true); //?? 7days // valueaxis.setFixedAutoRange(604800000D); valueaxis = xyplot.getRangeAxis(); valueaxis.setLabelFont(new Font("", Font.BOLD, 14)); valueaxis.setLabelPaint(line0render.getSeriesPaint(0)); valueaxis2.setLabelPaint(line1render.getSeriesPaint(0)); jfreechart.getTitle().setFont(new Font("", Font.BOLD, 20));// jfreechart.getLegend().setItemFont(new Font("", Font.ITALIC, 15)); xyplot.getRenderer(0).setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator("{1}, {2}", new SimpleDateFormat("MM-dd HH:mm:ss"), new DecimalFormat("0.0000"))); xyplot.getRenderer(1).setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator("{1}, {2}", new SimpleDateFormat("MM-dd HH:mm:ss"), new DecimalFormat("0.0000"))); chartPanel = new ChartPanel(jfreechart); initChartMenu(); // chartPanel.getPopupMenu().add(jmenuitem2); // chartPanel.getPopupMenu().getPopupMenuListeners(); chartPanel.setSize(950, 620); chartPanel.setPreferredSize(new Dimension(950, 620)); jPanel_Show.add(chartPanel, BorderLayout.CENTER); }
From source file:fr.paris.lutece.plugins.form.utils.FormUtils.java
/** * create a JFreeChart Graph function of the statistic form submit * @param listStatistic the list of statistic of form submit * @param strLabelX the label of axis x/* w ww .j a v a 2s .c o m*/ * @param strLableY the label of axis x * @param strTimesUnit the times unit of axis x(Day,Week,Month) * @return a JFreeChart Graph function of the statistic form submit */ public static JFreeChart createXYGraph(List<StatisticFormSubmit> listStatistic, String strLabelX, String strLableY, String strTimesUnit) { XYDataset xyDataset = createDataset(listStatistic, strTimesUnit); JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(EMPTY_STRING, strLabelX, strLableY, xyDataset, false, false, false); jfreechart.setBackgroundPaint(Color.white); XYPlot xyplot = jfreechart.getXYPlot(); //xyplot.setBackgroundPaint(Color.gray); //xyplot.setRangeGridlinesVisible(true); xyplot.setBackgroundPaint(Color.white); xyplot.setBackgroundPaint(Color.lightGray); xyplot.setDomainGridlinePaint(Color.white); xyplot.setRangeGridlinePaint(Color.white); // DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis( ); // dateaxis.setLowerMargin(0); // DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy"); // dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7,formatter)); //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7)); //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7)); //dateaxis.setMinimumDate((Date)listStatistic.get(0).getTimesUnit()); //dateaxis.setMaximumDate((Date)listStatistic.get(listStatistic.size()-1).getTimesUnit()); //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1)); //dateaxis.setTickUnit(new DateTickUnit(1, 1, DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH))); //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1, new SimpleDateFormat("MM/YY"))); //dateaxis.setVerticalTickLabels( true ); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); renderer.setBaseShapesVisible(true); renderer.setSeriesFillPaint(0, Color.RED); renderer.setUseFillPaint(true); // renderer.setToolTipGenerator( new StandardXYToolTipGenerator( "{0} {1} {2}", // DateFormat.getDateInstance( DateFormat.SHORT, Locale.FRENCH ), NumberFormat.getInstance( ) ) ); // // ChartRenderingInfo info = new ChartRenderingInfo( new StandardEntityCollection( ) ); return jfreechart; }
From source file:skyc.ViewContent.java
private void b2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b2ActionPerformed // TODO add your handling code here: Statement stmt = null;// w w w.j a v a 2 s . co m Connection currentCon = null; boolean rs = false; ResultSet rs2; String color; int Orderby = jComboBox2.getSelectedIndex(); if (Orderby == 0) color = "r"; else if (Orderby == 1) color = "b"; else color = "g"; TimeSeries series = new TimeSeries("", Day.class); currentCon = ConnectionManager.getConnection(); try { stmt = currentCon.createStatement(); } catch (SQLException ex) { Logger.getLogger(ViewContent.class.getName()).log(Level.SEVERE, null, ex); } String SelectQuery = "Select * from pics WHERE location = '" + location + "' AND date >= '" + fromstring + "' AND date <= '" + tostring + "' ORDER BY '" + color + "'"; try { rs2 = stmt.executeQuery(SelectQuery); int i = 10; while (rs2.next()) { String r = rs2.getString("r").toString(); String g = rs2.getString("g").toString(); String b = rs2.getString("b").toString(); String path = rs2.getString("pic_path").toString(); ImageIcon imgThisImg = new ImageIcon(path); StringTokenizer st = new StringTokenizer(r, "."); r = st.nextToken(); st = new StringTokenizer(g, "."); g = st.nextToken(); st = new StringTokenizer(b, "."); b = st.nextToken(); series.add(new Day(new Date("2015/04/" + i)), Integer.parseInt(b)); i++; // p1.setBackground(new Color(Integer.parseInt(r),Integer.parseInt(g),Integer.parseInt(b)) ); } } catch (SQLException e2) { System.out.println("SQL error is: " + e2); } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart("Change of sky color", // Title "Day", // X-Axis label "Ratio", // Y-Axis label dataset, // Dataset true, // Show legend true, //tooltips false //url ); saveChart(chart); gr h = new gr(); h.setVisible(true); }
From source file:se.technipelago.weather.chart.Generator.java
private JFreeChart createLineChart(final String title, final String valueLabel, final XYDataset dataset) { final JFreeChart chart = ChartFactory.createTimeSeriesChart(title, null, valueLabel, dataset, false, false, false);/* ww w . j a v a 2s.c o m*/ if (dataset.getItemCount(0) < 30) { final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); final XYPlot plot = (XYPlot) chart.getPlot(); plot.setRenderer(renderer); } return chart; }
From source file:lucee.runtime.tag.Chart.java
private void chartTimeLine() throws PageException, IOException { // create the chart... final JFreeChart chart = ChartFactory.createTimeSeriesChart(title, xaxistitle, yaxistitle, createTimeSeriesCollection(), false, true, false); Plot p = chart.getPlot();/*from w w w . java2 s . c o m*/ Font _font = getFont(); // settings setMarker(chart, p); setBackground(chart, p); setBorder(chart, p); set3d(p); setFont(chart, _font); setLabelFormat(chart); setLegend(chart, p, _font); setTooltip(chart); setScale(chart); setAxis(chart); setColor(chart); writeOut(chart); }
From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.MeasurementGraphAction2.java
JFreeChart labChartRef(String demographicNo, String typeIdName, String typeIdName2, String patientName, String chartTitle) {/* w w w . j a va2 s. c om*/ org.jfree.data.time.TimeSeriesCollection dataset = new org.jfree.data.time.TimeSeriesCollection(); ArrayList<EctMeasurementsDataBean> list = getList(demographicNo, typeIdName); String typeYAxisName = ""; ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>(); if (typeIdName.equals("BP")) { log.debug("Using BP LOGIC FOR type 1 "); EctMeasurementsDataBean sampleLine = list.get(0); typeYAxisName = sampleLine.getTypeDescription(); TimeSeries systolic = new TimeSeries("Systolic", Day.class); TimeSeries diastolic = new TimeSeries("Diastolic", Day.class); for (EctMeasurementsDataBean mdb : list) { // dataVector) { String[] str = mdb.getDataField().split("/"); systolic.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(str[0])); diastolic.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(str[1])); } dataset.addSeries(diastolic); dataset.addSeries(systolic); } else { log.debug("Not Using BP LOGIC FOR type 1 "); // get the name from the TimeSeries EctMeasurementsDataBean sampleLine = list.get(0); String typeLegendName = sampleLine.getTypeDisplayName(); typeYAxisName = sampleLine.getTypeDescription(); // this should be the type of measurement TimeSeries newSeries = new TimeSeries(typeLegendName, Day.class); for (EctMeasurementsDataBean mdb : list) { //dataVector) { newSeries.addOrUpdate(new Day(mdb.getDateObservedAsDate()), Double.parseDouble(mdb.getDataField())); try { Hashtable h = getMeasurementsExt(mdb.getId()); if (h != null && h.containsKey("minimum")) { String min = (String) h.get("minimum"); String max = (String) h.get("maximum"); double open = Double.parseDouble(min.trim()); double high = Double.parseDouble(max.trim()); double low = Double.parseDouble(min.trim()); double close = Double.parseDouble(max.trim()); double volume = 1045; dataItems .add(new OHLCDataItem(mdb.getDateObservedAsDate(), open, high, low, close, volume)); } } catch (Exception et) { MiscUtils.getLogger().error("Error", et); } } dataset.addSeries(newSeries); } JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, "Days", typeYAxisName, dataset, true, true, true); XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setAutoRange(true); log.debug("LEN " + plot.getDomainAxis().getLowerBound() + " ddd " + plot.getDomainAxis().getUpperMargin() + " eee " + plot.getDomainAxis().getLowerMargin()); plot.getDomainAxis().setUpperMargin(plot.getDomainAxis().getUpperMargin() * 6); plot.getDomainAxis().setLowerMargin(plot.getDomainAxis().getLowerMargin() * 6); plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 1.7); plot.getDomainAxis().setUpperMargin(0.9); plot.getDomainAxis().setLowerMargin(0.9); plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 4); ValueAxis va = plot.getRangeAxis(); va.setAutoRange(true); XYItemRenderer renderer = plot.getRenderer(); //DateFormat.getInstance() XYItemLabelGenerator generator = new StandardXYItemLabelGenerator("{1} \n {2}", new SimpleDateFormat("yyyy.MM.dd"), new DecimalFormat("0.00")); renderer.setSeriesItemLabelGenerator(0, generator);//setLabelGenerator(generator); renderer.setBaseItemLabelsVisible(true); plot.setBackgroundPaint(Color.WHITE); plot.setDomainCrosshairPaint(Color.GRAY); if (renderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) renderer; rend.setBaseShapesVisible(true); rend.setBaseShapesFilled(true); } plot.setRenderer(renderer); if (dataItems != null && dataItems.size() > 0) { OHLCDataItem[] ohlc = dataItems.toArray(new OHLCDataItem[dataItems.size()]); XYDataset referenceRangeDataset = new DefaultOHLCDataset("Reference Range", ohlc); plot.setRenderer(1, setAxisAndDataSet(1, plot, plot.getRangeAxis(), referenceRangeDataset, Color.GREEN, new HighLowRenderer())); } ///// 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; }//from w w w .ja va 2 s. co m 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:org.jfree.chart.demo.XYBoxAnnotationDemo1.java
private static JFreeChart createChart(XYDataset xydataset) { JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("Breakdowns", "Production Date", "Hours of Operation", xydataset, true, true, false); jfreechart.setBackgroundPaint(Color.white); XYPlot xyplot = (XYPlot) jfreechart.getPlot(); XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); xylineandshaperenderer.setSeriesShape(0, new Rectangle(2, 2)); xylineandshaperenderer.setSeriesShape(1, new Rectangle(2, 2)); xylineandshaperenderer.setBaseLinesVisible(false); xylineandshaperenderer.setBaseShapesFilled(true); xylineandshaperenderer.setBaseShapesVisible(true); xylineandshaperenderer.setBaseToolTipGenerator(null); xylineandshaperenderer.setSeriesPaint(0, Color.blue); xylineandshaperenderer.setSeriesPaint(1, Color.red); xyplot.setDomainGridlineStroke(new BasicStroke(1.0F)); xyplot.setRangeGridlineStroke(new BasicStroke(1.0F)); NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis(); numberaxis.setTickUnit(new NumberTickUnit(50000D)); DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis(); dateaxis.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH, 1)); dateaxis.setDateFormatOverride(new SimpleDateFormat("MMM.yy")); dateaxis.setVerticalTickLabels(true); Color color = new Color(255, 0, 0, 60); Color color1 = new Color(0, 255, 0, 60); XYBoxAnnotation xyboxannotation = new XYBoxAnnotation((new Day(1, 1, 2004)).getMiddleMillisecond(), 0.0D, (new Day(31, 1, 2004)).getMiddleMillisecond(), 50000D, new BasicStroke(0.0F), color, color); xyboxannotation.setToolTipText("Value: 2.9"); xylineandshaperenderer.addAnnotation(xyboxannotation); xyboxannotation = new XYBoxAnnotation((new Day(1, 2, 2004)).getMiddleMillisecond(), 0.0D, (new Day(29, 2, 2004)).getMiddleMillisecond(), 50000D, new BasicStroke(0.0F), color, color); xyboxannotation.setToolTipText("Value: 2.5"); xylineandshaperenderer.addAnnotation(xyboxannotation); xyboxannotation = new XYBoxAnnotation((new Day(1, 5, 2004)).getMiddleMillisecond(), 50000D, (new Day(31, 5, 2004)).getMiddleMillisecond(), 100000D, new BasicStroke(0.0F), color, color); xyboxannotation.setToolTipText("Value: 1.8"); xylineandshaperenderer.addAnnotation(xyboxannotation); xyboxannotation = new XYBoxAnnotation((new Day(1, 6, 2005)).getMiddleMillisecond(), 0.0D, (new Day(30, 6, 2005)).getMiddleMillisecond(), 50000D, new BasicStroke(0.0F), color1, color1); xyboxannotation.setToolTipText("Value: 3.7"); xylineandshaperenderer.addAnnotation(xyboxannotation); return jfreechart; }
From source file:org.jfree.chart.demo.JFreeChartDemoBase.java
/** * Creates and returns a sample time series chart that will be displayed in a scroll pane. * * @return a sample time series chart.//from w w w . ja v a 2 s. c om */ public JFreeChart createTimeSeriesChartInScrollPane() { // create a default chart based on some sample data... final String title = this.resources.getString("test.scroll.title"); final String domain = this.resources.getString("test.scroll.domain"); final String range = this.resources.getString("test.scroll.range"); final String subtitleStr = this.resources.getString("test.scroll.subtitle"); final XYDataset data = DemoDatasetFactory.createTimeSeriesCollection2(); final JFreeChart chart = ChartFactory.createTimeSeriesChart(title, domain, range, data, true, true, false); // then customise it a little... final TextTitle subtitle = new TextTitle(subtitleStr, new Font("SansSerif", Font.BOLD, 12)); chart.addSubtitle(subtitle); chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.gray)); return chart; }