Search in sources :

Example 36 with NumberAxis

use of org.jfree.chart.axis.NumberAxis in project lotro-companion by dmorcellet.

the class CharacterLevelChartController method buildChart.

private JFreeChart buildChart() {
    String title = "Characters levelling";
    String timeAxisLabel = "Time";
    String valueAxisLabel = "Level";
    XYDataset xydataset = createDataset();
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, timeAxisLabel, valueAxisLabel, xydataset, true, true, false);
    Color foregroundColor = GuiFactory.getForegroundColor();
    Paint backgroundPaint = GuiFactory.getBackgroundPaint();
    jfreechart.setBackgroundPaint(backgroundPaint);
    TextTitle t = new TextTitle(title);
    t.setFont(t.getFont().deriveFont(24.0f));
    t.setPaint(foregroundColor);
    jfreechart.setTitle(t);
    XYPlot plot = jfreechart.getXYPlot();
    plot.setDomainPannable(false);
    XYToolTipGenerator tooltip = new StandardXYToolTipGenerator() {

        @Override
        public String generateLabelString(XYDataset dataset, int series, int item) {
            String name = (String) ((XYSeriesCollection) dataset).getSeriesKey(series);
            int level = (int) dataset.getYValue(series, item);
            double timestamp = dataset.getXValue(series, item);
            String date = Formats.getDateString(Long.valueOf((long) timestamp));
            return name + " - " + level + " (" + date + ")";
        }
    };
    XYItemRenderer renderer = plot.getRenderer();
    renderer.setBaseToolTipGenerator(tooltip);
    // Time axis
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    SimpleDateFormat sdf = Formats.getDateFormatter();
    axis.setDateFormatOverride(sdf);
    axis.setAxisLinePaint(foregroundColor);
    axis.setLabelPaint(foregroundColor);
    axis.setTickLabelPaint(foregroundColor);
    // Level axis
    NumberAxis valueAxis = (NumberAxis) plot.getRangeAxis();
    valueAxis.setAutoRange(true);
    valueAxis.setAxisLinePaint(foregroundColor);
    valueAxis.setLabelPaint(foregroundColor);
    valueAxis.setTickLabelPaint(foregroundColor);
    TickUnitSource ticks = getLevelTicks();
    valueAxis.setStandardTickUnits(ticks);
    LegendTitle legend = jfreechart.getLegend();
    legend.setPosition(RectangleEdge.BOTTOM);
    legend.setItemPaint(foregroundColor);
    legend.setBackgroundPaint(backgroundPaint);
    return jfreechart;
}
Also used : DateAxis(org.jfree.chart.axis.DateAxis) NumberAxis(org.jfree.chart.axis.NumberAxis) Color(java.awt.Color) TickUnitSource(org.jfree.chart.axis.TickUnitSource) LegendTitle(org.jfree.chart.title.LegendTitle) Paint(java.awt.Paint) JFreeChart(org.jfree.chart.JFreeChart) Paint(java.awt.Paint) TextTitle(org.jfree.chart.title.TextTitle) StandardXYToolTipGenerator(org.jfree.chart.labels.StandardXYToolTipGenerator) XYPlot(org.jfree.chart.plot.XYPlot) XYDataset(org.jfree.data.xy.XYDataset) StandardXYToolTipGenerator(org.jfree.chart.labels.StandardXYToolTipGenerator) XYToolTipGenerator(org.jfree.chart.labels.XYToolTipGenerator) XYItemRenderer(org.jfree.chart.renderer.xy.XYItemRenderer) SimpleDateFormat(java.text.SimpleDateFormat)

Example 37 with NumberAxis

use of org.jfree.chart.axis.NumberAxis in project lotro-companion by dmorcellet.

the class CraftingHistoryChartController method buildChart.

private JFreeChart buildChart() {
    String title = "";
    if (_showTitle) {
        title = _stats.getProfession().getLabel();
    }
    updateData();
    JFreeChart jfreechart = ChartFactory.createXYStepChart(title, "Time", "Tier", _data, PlotOrientation.VERTICAL, true, true, false);
    Color foregroundColor = GuiFactory.getForegroundColor();
    Paint backgroundPaint = GuiFactory.getBackgroundPaint();
    jfreechart.setBackgroundPaint(backgroundPaint);
    TextTitle t = new TextTitle(title);
    t.setFont(t.getFont().deriveFont(24.0f));
    t.setPaint(foregroundColor);
    jfreechart.setTitle(t);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setDomainPannable(false);
    XYStepAreaRenderer xysteparearenderer = new XYStepAreaRenderer(XYStepAreaRenderer.AREA_AND_SHAPES);
    XYToolTipGenerator tooltip = new StandardXYToolTipGenerator() {

        @Override
        public String generateLabelString(XYDataset dataset, int series, int item) {
            String label;
            int tier = (int) dataset.getYValue(series, item);
            if (tier == 0) {
                label = "Started profession";
            } else {
                CraftingLevel level = CraftingLevel.getByTier(tier);
                if (level != null) {
                    if (series == 0)
                        label = level.getMastery().getLabel();
                    else if (series == 1)
                        label = level.getProficiency().getLabel();
                    else
                        label = "???";
                } else {
                    label = "???";
                }
            }
            double timestamp = dataset.getXValue(series, item);
            String date = Formats.getDateString(Long.valueOf((long) timestamp));
            return label + " (" + date + ")";
        }
    };
    xysteparearenderer.setBaseToolTipGenerator(tooltip);
    xysteparearenderer.setSeriesPaint(0, new Color(255, 235, 31));
    xysteparearenderer.setSeriesPaint(1, new Color(130, 80, 57));
    xyplot.setRenderer(xysteparearenderer);
    DateAxis axis = (DateAxis) xyplot.getDomainAxis();
    SimpleDateFormat sdf = Formats.getDateFormatter();
    axis.setDateFormatOverride(sdf);
    axis.setAxisLinePaint(foregroundColor);
    axis.setLabelPaint(foregroundColor);
    axis.setTickLabelPaint(foregroundColor);
    NumberAxis valueAxis = (NumberAxis) xyplot.getRangeAxis();
    valueAxis.setAutoRange(false);
    valueAxis.setAxisLinePaint(foregroundColor);
    valueAxis.setLabelPaint(foregroundColor);
    valueAxis.setTickLabelPaint(foregroundColor);
    CraftingLevel maxLevel = CraftingLevel.getMaximumLevel();
    valueAxis.setRange(0, maxLevel.getTier());
    NumberFormat nf = new NumberFormat() {

        private String format(int number) {
            CraftingLevel level = CraftingLevel.getByTier(number);
            String ret = (level != null) ? level.getProficiency().getLabel() : "???";
            return ret;
        }

        @Override
        public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
            return toAppendTo.append(format((int) number));
        }

        @Override
        public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
            return toAppendTo.append(format((int) number));
        }

        @Override
        public Number parse(String source, ParsePosition parsePosition) {
            return null;
        }
    };
    valueAxis.setNumberFormatOverride(nf);
    LegendTitle legend = jfreechart.getLegend();
    legend.setItemPaint(foregroundColor);
    legend.setBackgroundPaint(backgroundPaint);
    return jfreechart;
}
Also used : DateAxis(org.jfree.chart.axis.DateAxis) NumberAxis(org.jfree.chart.axis.NumberAxis) Color(java.awt.Color) XYStepAreaRenderer(org.jfree.chart.renderer.xy.XYStepAreaRenderer) LegendTitle(org.jfree.chart.title.LegendTitle) Paint(java.awt.Paint) FieldPosition(java.text.FieldPosition) JFreeChart(org.jfree.chart.JFreeChart) Paint(java.awt.Paint) TextTitle(org.jfree.chart.title.TextTitle) StandardXYToolTipGenerator(org.jfree.chart.labels.StandardXYToolTipGenerator) XYPlot(org.jfree.chart.plot.XYPlot) XYDataset(org.jfree.data.xy.XYDataset) StandardXYToolTipGenerator(org.jfree.chart.labels.StandardXYToolTipGenerator) XYToolTipGenerator(org.jfree.chart.labels.XYToolTipGenerator) CraftingLevel(delta.games.lotro.lore.crafting.CraftingLevel) SimpleDateFormat(java.text.SimpleDateFormat) NumberFormat(java.text.NumberFormat) ParsePosition(java.text.ParsePosition)

Example 38 with NumberAxis

use of org.jfree.chart.axis.NumberAxis in project lotro-companion by dmorcellet.

the class FactionHistoryChartController method buildChart.

private JFreeChart buildChart() {
    String title = "";
    if (_showTitle) {
        title = _stats.getFaction().getName();
    }
    updateData();
    JFreeChart jfreechart = ChartFactory.createXYStepChart(title, "Time", "Level", _data, PlotOrientation.VERTICAL, true, true, false);
    Color foregroundColor = GuiFactory.getForegroundColor();
    Paint backgroundPaint = GuiFactory.getBackgroundPaint();
    jfreechart.setBackgroundPaint(backgroundPaint);
    TextTitle t = new TextTitle(title);
    t.setFont(t.getFont().deriveFont(24.0f));
    t.setPaint(foregroundColor);
    jfreechart.setTitle(t);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setDomainPannable(false);
    XYStepAreaRenderer xysteparearenderer = new XYStepAreaRenderer(XYStepAreaRenderer.AREA_AND_SHAPES);
    Faction faction = _stats.getFaction();
    final FactionLevel[] levels = faction.getLevels();
    XYToolTipGenerator tooltip = new StandardXYToolTipGenerator() {

        @Override
        public String generateLabelString(XYDataset dataset, int series, int item) {
            String label = "???";
            int tier = (int) dataset.getYValue(series, item);
            for (FactionLevel level : levels) {
                if (level.getValue() == tier) {
                    label = level.getName();
                }
            }
            double timestamp = dataset.getXValue(series, item);
            String date = Formats.getDateString(Long.valueOf((long) timestamp));
            return label + " (" + date + ")";
        }
    };
    xysteparearenderer.setBaseToolTipGenerator(tooltip);
    xysteparearenderer.setSeriesPaint(0, new Color(0, 0, 255));
    xyplot.setRenderer(xysteparearenderer);
    DateAxis axis = (DateAxis) xyplot.getDomainAxis();
    SimpleDateFormat sdf = Formats.getDateFormatter();
    axis.setDateFormatOverride(sdf);
    axis.setAxisLinePaint(foregroundColor);
    axis.setLabelPaint(foregroundColor);
    axis.setTickLabelPaint(foregroundColor);
    NumberAxis valueAxis = (NumberAxis) xyplot.getRangeAxis();
    valueAxis.setAutoRange(false);
    valueAxis.setAxisLinePaint(foregroundColor);
    valueAxis.setLabelPaint(foregroundColor);
    valueAxis.setTickLabelPaint(foregroundColor);
    final int min = levels[0].getValue();
    int max = levels[levels.length - 1].getValue();
    valueAxis.setRange(min, max);
    NumberFormat nf = new NumberFormat() {

        private String format(int number) {
            String ret = levels[number - min].getName();
            return ret;
        }

        @Override
        public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
            return toAppendTo.append(format((int) number));
        }

        @Override
        public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
            return toAppendTo.append(format((int) number));
        }

        @Override
        public Number parse(String source, ParsePosition parsePosition) {
            return null;
        }
    };
    valueAxis.setNumberFormatOverride(nf);
    LegendTitle legend = jfreechart.getLegend();
    legend.setItemPaint(foregroundColor);
    legend.setBackgroundPaint(backgroundPaint);
    return jfreechart;
}
Also used : DateAxis(org.jfree.chart.axis.DateAxis) NumberAxis(org.jfree.chart.axis.NumberAxis) Color(java.awt.Color) XYStepAreaRenderer(org.jfree.chart.renderer.xy.XYStepAreaRenderer) LegendTitle(org.jfree.chart.title.LegendTitle) Paint(java.awt.Paint) FieldPosition(java.text.FieldPosition) JFreeChart(org.jfree.chart.JFreeChart) FactionLevel(delta.games.lotro.lore.reputation.FactionLevel) Paint(java.awt.Paint) TextTitle(org.jfree.chart.title.TextTitle) StandardXYToolTipGenerator(org.jfree.chart.labels.StandardXYToolTipGenerator) XYPlot(org.jfree.chart.plot.XYPlot) XYDataset(org.jfree.data.xy.XYDataset) StandardXYToolTipGenerator(org.jfree.chart.labels.StandardXYToolTipGenerator) XYToolTipGenerator(org.jfree.chart.labels.XYToolTipGenerator) SimpleDateFormat(java.text.SimpleDateFormat) Faction(delta.games.lotro.lore.reputation.Faction) NumberFormat(java.text.NumberFormat) ParsePosition(java.text.ParsePosition)

Example 39 with NumberAxis

use of org.jfree.chart.axis.NumberAxis in project Gemma by PavlidisLab.

the class ExpressionExperimentQCController method writeDetailedFactorAnalysis.

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;
    }
    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());
    // need the experimental design
    ee = expressionExperimentService.thawLite(ee);
    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);
            // unique?
            String plotname = (efs.get(efId) == null ? "?" : efs.get(efId)) + " " + xaxisLabel;
            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) {
                            // is this all we need to do?
                            continue;
                        }
                        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);
            // has no effect, need dotheight.
            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));
            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;
}
Also used : TimeSeries(org.jfree.data.time.TimeSeries) Ellipse2D(java.awt.geom.Ellipse2D) DoubleArrayList(cern.colt.list.DoubleArrayList) List(java.util.List) XYItemRenderer(org.jfree.chart.renderer.xy.XYItemRenderer) DefaultMultiValueCategoryDataset(org.jfree.data.statistics.DefaultMultiValueCategoryDataset) Hour(org.jfree.data.time.Hour) XYDotRenderer(org.jfree.chart.renderer.xy.XYDotRenderer) CategoryPlot(org.jfree.chart.plot.CategoryPlot) XYPlot(org.jfree.chart.plot.XYPlot) NumberAxis(org.jfree.chart.axis.NumberAxis) ExperimentalFactor(ubic.gemma.model.expression.experiment.ExperimentalFactor) SVDValueObject(ubic.gemma.core.analysis.preprocess.svd.SVDValueObject) BufferedImage(java.awt.image.BufferedImage) Minute(org.jfree.data.time.Minute) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) ValueAxis(org.jfree.chart.axis.ValueAxis) DefaultXYDataset(org.jfree.data.xy.DefaultXYDataset) JFreeChart(org.jfree.chart.JFreeChart) CategoryAxis(org.jfree.chart.axis.CategoryAxis) ScatterRenderer(org.jfree.chart.renderer.category.ScatterRenderer)

Example 40 with NumberAxis

use of org.jfree.chart.axis.NumberAxis in project Gemma by PavlidisLab.

the class ExpressionExperimentQCController method writeMeanVariance.

/**
 * @param os  response output stream
 * @param mvr MeanVarianceRelation object to plot
 * @return true if mvr data points were plotted
 */
private boolean writeMeanVariance(OutputStream os, MeanVarianceRelation mvr, Double size) throws Exception {
    // if number of datapoints > THRESHOLD then alpha = TRANSLUCENT, else alpha = OPAQUE
    final int THRESHOLD = 1000;
    final int TRANSLUCENT = 50;
    final int OPAQUE = 255;
    // Set maximum plot range to Y_MAX + YRANGE * OFFSET to leave some extra white space
    final double OFFSET_FACTOR = 0.05f;
    // set the final image size to be the minimum of MAX_IMAGE_SIZE_PX or size
    final int MAX_IMAGE_SIZE_PX = 5;
    if (mvr == null) {
        return false;
    }
    // get data points
    XYSeriesCollection collection = this.getMeanVariance(mvr);
    if (collection.getSeries().size() == 0) {
        return false;
    }
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart chart = ChartFactory.createScatterPlot("", "mean (log2)", "variance (log2)", collection, PlotOrientation.VERTICAL, false, false, false);
    // adjust colors and shapes
    XYRegressionRenderer renderer = new XYRegressionRenderer();
    renderer.setBasePaint(Color.white);
    int alpha = collection.getSeries(0).getItemCount() > THRESHOLD ? TRANSLUCENT : OPAQUE;
    renderer.setSeriesPaint(0, new Color(0, 0, 0, alpha));
    renderer.setSeriesPaint(1, Color.red);
    renderer.setSeriesStroke(1, new BasicStroke(1));
    renderer.setSeriesShape(0, new Ellipse2D.Double(4, 4, 4, 4));
    renderer.setSeriesShapesFilled(0, false);
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesLinesVisible(1, true);
    renderer.setSeriesShapesVisible(1, false);
    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(renderer);
    plot.setRangeGridlinesVisible(false);
    plot.setDomainGridlinesVisible(false);
    // adjust the chart domain and ranges
    double yRange = collection.getSeries(0).getMaxY() - collection.getSeries(0).getMinY();
    double xRange = collection.getSeries(0).getMaxX() - collection.getSeries(0).getMinX();
    double ybuffer = (yRange) * OFFSET_FACTOR;
    double xbuffer = (xRange) * OFFSET_FACTOR;
    double newYMin = collection.getSeries(0).getMinY() - ybuffer;
    double newYMax = collection.getSeries(0).getMaxY() + ybuffer;
    double newXMin = collection.getSeries(0).getMinX() - xbuffer;
    double newXMax = collection.getSeries(0).getMaxX() + xbuffer;
    ValueAxis yAxis = new NumberAxis("Variance");
    yAxis.setRange(newYMin, newYMax);
    ValueAxis xAxis = new NumberAxis("Mean");
    xAxis.setRange(newXMin, newXMax);
    chart.getXYPlot().setRangeAxis(yAxis);
    chart.getXYPlot().setDomainAxis(xAxis);
    int finalSize = (int) Math.min(MAX_IMAGE_SIZE_PX * ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX, size * ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX);
    ChartUtilities.writeChartAsPNG(os, chart, finalSize, finalSize);
    return true;
}
Also used : NumberAxis(org.jfree.chart.axis.NumberAxis) XYPlot(org.jfree.chart.plot.XYPlot) ValueAxis(org.jfree.chart.axis.ValueAxis) XYSeriesCollection(org.jfree.data.xy.XYSeriesCollection) JFreeChart(org.jfree.chart.JFreeChart) Ellipse2D(java.awt.geom.Ellipse2D)

Aggregations

NumberAxis (org.jfree.chart.axis.NumberAxis)260 JFreeChart (org.jfree.chart.JFreeChart)147 Test (org.junit.Test)118 XYPlot (org.jfree.chart.plot.XYPlot)99 CategoryAxis (org.jfree.chart.axis.CategoryAxis)95 CategoryPlot (org.jfree.chart.plot.CategoryPlot)80 ValueAxis (org.jfree.chart.axis.ValueAxis)46 DefaultCategoryDataset (org.jfree.data.category.DefaultCategoryDataset)44 XYLineAndShapeRenderer (org.jfree.chart.renderer.xy.XYLineAndShapeRenderer)40 XYSeriesCollection (org.jfree.data.xy.XYSeriesCollection)39 XYSeries (org.jfree.data.xy.XYSeries)38 BarRenderer (org.jfree.chart.renderer.category.BarRenderer)37 XYItemRenderer (org.jfree.chart.renderer.xy.XYItemRenderer)30 XYDataset (org.jfree.data.xy.XYDataset)30 Color (java.awt.Color)28 DateAxis (org.jfree.chart.axis.DateAxis)27 StandardXYToolTipGenerator (org.jfree.chart.labels.StandardXYToolTipGenerator)27 BasicStroke (java.awt.BasicStroke)25 StandardXYItemRenderer (org.jfree.chart.renderer.xy.StandardXYItemRenderer)24 CategoryDataset (org.jfree.data.category.CategoryDataset)21