private static LegendTitle createLegend(String legend1Text, String legend2Text) { final LegendItemCollection legendItems = new LegendItemCollection(); FontRenderContext frc = new FontRenderContext(null, true, true); Font legenfont = new Font(Font.SANS_SERIF, Font.BOLD, 12); GlyphVector gv = legenfont.createGlyphVector(frc, new char[] {'X', 'X'}); Shape shape = gv.getVisualBounds(); Rectangle2D bounds = shape.getBounds2D(); HatchedRectangle hatchShape = new HatchedRectangle( bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 5, 5); { LegendItem li = new LegendItem(legend1Text, null, null, null, hatchShape, Color.black); li.setLabelFont(legenfont); legendItems.add(li); } { LegendItem li = new LegendItem(legend2Text, null, null, null, shape, Color.black); li.setLabelFont(legenfont); legendItems.add(li); } LegendTitle legend = new LegendTitle( new LegendItemSource() { @Override public LegendItemCollection getLegendItems() { return legendItems; } }); legend.setPosition(RectangleEdge.BOTTOM); legend.setMargin(new RectangleInsets(0, 30, 0, 0)); legend.setPadding(RectangleInsets.ZERO_INSETS); legend.setLegendItemGraphicPadding(new RectangleInsets(0, 20, 0, 0)); return legend; }
public LegendItemCollection getLegendItems(PlotInstance plotInstance) { PlotConfiguration plotConfiguration = plotInstance.getCurrentPlotConfigurationClone(); LegendItemCollection legendItemCollection = new LegendItemCollection(); // Get list of ValueSources which get an own legend entry. // These are those ValueSources, for which useSeriesFormatForDimension() returns true // for at least one dimension (not considering X and VALUE). // get all values sources List<ValueSource> allValueSources = plotConfiguration.getAllValueSources(); // add the plots heading (if we have any value sources) if (!allValueSources.isEmpty()) { legendItemCollection.add( createTitleLegendItem( I18N.getGUILabel("plotter.legend.plots_heading.label") + ":", plotConfiguration)); } // now find those value sources for which we need a legend entry, // and also remember which dimensions are shown in the legend entry (color, shape, ...) for (ValueSource valueSource : allValueSources) { CustomLegendItem legendItem = createValueSourceLegendItem(plotConfiguration, valueSource); if (legendItem != null) { legendItemCollection.add(legendItem); } } List<Set<PlotDimension>> dimensionsWithLegend = findCompatibleDimensions(plotConfiguration, allValueSources); // create legend items for DimensionConfigs for (Set<PlotDimension> dimensionSet : dimensionsWithLegend) { PlotDimension aDimension = dimensionSet.iterator().next(); DimensionConfig dimensionConfig = plotConfiguration.getDimensionConfig(aDimension); createDimensionConfigLegendItem( plotInstance, (DefaultDimensionConfig) dimensionConfig, dimensionSet, legendItemCollection); } return legendItemCollection; }
/** * Creates the headings for the dimension config items ( like "Color (attribute X)" ) and adds it * to legendItemCollection. */ private void createDimensionTitleLegendItem( PlotInstance plotInstance, Set<PlotDimension> dimensionSet, LegendItemCollection legendItemCollection) { PlotConfiguration plotConfig = plotInstance.getCurrentPlotConfigurationClone(); StringBuilder titleBuilder = new StringBuilder(); boolean first = true; boolean showDimensionType = plotConfig.getLegendConfiguration().isShowDimensionType(); if (showDimensionType) { for (PlotDimension dimension : dimensionSet) { if (!first) { titleBuilder.append(", "); } titleBuilder.append(dimension.getShortName()); first = false; } } if (showDimensionType) { titleBuilder.append(" ("); } // get unique dimension labels: Set<String> uniqueDimensionLabels = new HashSet<String>(); first = true; for (PlotDimension dimension : dimensionSet) { DefaultDimensionConfig dimensionConfig = (DefaultDimensionConfig) plotConfig.getDimensionConfig(dimension); String label = dimensionConfig.getLabel(); if (label == null) { label = I18N.getGUILabel("plotter.unnamed_value_label"); } if (!uniqueDimensionLabels.contains(label)) { if (!first) { titleBuilder.append(", "); first = false; } titleBuilder.append(label); uniqueDimensionLabels.add(label); } } if (showDimensionType) { titleBuilder.append(")"); } titleBuilder.append(": "); legendItemCollection.add(createTitleLegendItem(titleBuilder.toString(), plotConfig)); }
/** * Returns a (possibly empty) collection of legend items for the series that this renderer is * responsible for drawing. * * @return The legend item collection (never <code>null</code>). */ public LegendItemCollection getLegendItems() { if (this.plot == null) { return new LegendItemCollection(); } LegendItemCollection result = new LegendItemCollection(); int index = this.plot.getIndexOf(this); CategoryDataset dataset = this.plot.getDataset(index); if (dataset != null) { int seriesCount = dataset.getRowCount(); for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } return result; }
/** * Returns an item for each interval. * * @return A collection of legend items. */ public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); Iterator iterator = this.intervals.iterator(); while (iterator.hasNext()) { MeterInterval mi = (MeterInterval) iterator.next(); Paint color = mi.getBackgroundPaint(); if (color == null) { color = mi.getOutlinePaint(); } LegendItem item = new LegendItem( mi.getLabel(), mi.getLabel(), null, null, new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0), color); result.add(item); } return result; }
public void updateAndSortLegend(LegendItemCollection legendItemsOld) { HashMap<String, LegendItem> oldIndexes = new HashMap<String, LegendItem>(); // Finding old indexes and saving them for sorting (not including those starting with "var" for (int i = 0; i < legendItemsOld.getItemCount(); i++) { LegendItem item = legendItemsOld.get(i); if (!item.getLabel().equals("var")) { oldIndexes.put(trimLabel(item.getLabel()), item); } } // Sorting the new legend final LegendItemCollection legendItemsNew = new LegendItemCollection(); Object[] keys = oldIndexes.keySet().toArray(); Arrays.sort(keys); for (Object key : keys) { legendItemsNew.add(oldIndexes.get(key)); } LegendItemSource source = new LegendItemSource() { LegendItemCollection lic = new LegendItemCollection(); { lic.addAll(legendItemsNew); } public LegendItemCollection getLegendItems() { return lic; } }; // Forcing legend to be in bottom LegendTitle legend = new LegendTitle(source); legend.setPosition(RectangleEdge.BOTTOM); legend.setBorder(1, 1, 1, 1); chart.removeLegend(); chart.addLegend(legend); }
/** * Returns a collection of legend items for the pie chart. The text for the labels is generated by * the provided label generators * * @return The legend items. */ public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); if (getDataset() != null) { List keys = null; prefetchSectionPaints(); if (getDataExtractOrder() == TableOrder.BY_ROW) { keys = getDataset().getColumnKeys(); } else if (getDataExtractOrder() == TableOrder.BY_COLUMN) { keys = getDataset().getRowKeys(); } if (keys != null) { int section = 0; Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); String label = null; // Use legend label generator !!! if (getDataExtractOrder() == TableOrder.BY_COLUMN) { int row = getDataset().getRowIndex(key); label = getLegendItemLabelGenerator().generateRowLabel(getDataset(), row); } else if (getDataExtractOrder() == TableOrder.BY_ROW) { int column = getDataset().getColumnIndex(key); label = getLegendItemLabelGenerator().generateColumnLabel(getDataset(), column); } if (label != null) { String description = label; Paint paint = (Paint) sectionPaints.get(key); LegendItem item = new LegendItem( label, description, null, null, Plot.DEFAULT_LEGEND_ITEM_CIRCLE, paint, Plot.DEFAULT_OUTLINE_STROKE, paint); item.setDataset(getDataset()); result.add(item); } section++; } } if (getLimit() > 0.0) { result.add( new LegendItem( getAggregatedItemsKey().toString(), getAggregatedItemsKey().toString(), null, null, Plot.DEFAULT_LEGEND_ITEM_CIRCLE, getAggregatedItemsPaint(), Plot.DEFAULT_OUTLINE_STROKE, getAggregatedItemsPaint())); } } return result; }
/** * Creates a sample chart. * * @param dataset the dataset. * @return The chart. */ private JFreeChart createChart(CategoryDataset dataset) { // create the chart... JFreeChart chart = ChartFactory.createStackedBarChart( "Public Opinion : Torture of Prisoners", "Country", // domain axis label "%", // range axis label dataset, // data PlotOrientation.HORIZONTAL, // orientation false, // include legend true, // tooltips? false // URLs? ); // set the background color for the chart... chart.setBackgroundPaint(Color.white); chart.getTitle().setMargin(2.0, 0.0, 0.0, 0.0); TextTitle tt = new TextTitle( "Source: http://news.bbc.co.uk/1/hi/world/6063386.stm", new Font("Dialog", Font.PLAIN, 11)); tt.setPosition(RectangleEdge.BOTTOM); tt.setHorizontalAlignment(HorizontalAlignment.RIGHT); tt.setMargin(0.0, 0.0, 4.0, 4.0); chart.addSubtitle(tt); TextTitle t = new TextTitle( "(*) Across 27,000 respondents in 25 countries", new Font("Dialog", Font.PLAIN, 11)); t.setPosition(RectangleEdge.BOTTOM); t.setHorizontalAlignment(HorizontalAlignment.RIGHT); t.setMargin(4.0, 0.0, 2.0, 4.0); chart.addSubtitle(t); // get a reference to the plot for further customisation... CategoryPlot plot = (CategoryPlot) chart.getPlot(); LegendItemCollection items = new LegendItemCollection(); items.add( new LegendItem( "Against all torture", null, null, null, new Rectangle2D.Double(-6.0, -3.0, 12.0, 6.0), Color.green)); items.add( new LegendItem( "Some degree permissible", null, null, null, new Rectangle2D.Double(-6.0, -3.0, 12.0, 6.0), Color.red)); plot.setFixedLegendItems(items); plot.setInsets(new RectangleInsets(5, 5, 5, 20)); LegendTitle legend = new LegendTitle(plot); legend.setPosition(RectangleEdge.BOTTOM); chart.addSubtitle(legend); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinePaint(Color.white); // set the range axis to display integers only... NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setUpperMargin(0.0); // disable bar outlines... BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setDrawBarOutline(false); // set up gradient paints for series... GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0)); Paint gp1 = new Color(0, 0, 0, 0); GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0)); // renderer.setSeriesPaint(0, gp0); renderer.setSeriesPaint(0, Color.green); renderer.setSeriesPaint(1, gp1); // renderer.setSeriesPaint(2, gp2); renderer.setSeriesPaint(2, Color.red); return chart; }
private void createCategoricalLegendItems( PlotInstance plotInstance, Set<PlotDimension> dimensionSet, LegendItemCollection legendItemCollection, Iterable<Double> values) { createDimensionTitleLegendItem(plotInstance, dimensionSet, legendItemCollection); PlotConfiguration plotConfig = plotInstance.getCurrentPlotConfigurationClone(); Shape defaultShape = new Ellipse2D.Float(-5f, -5f, 10f, 10f); Color defaultOutlineColor = PlotConfiguration.DEFAULT_OUTLINE_COLOR; ColorProvider colorProvider = null; ShapeProvider shapeProvider = null; SizeProvider sizeProvider = null; DefaultDimensionConfig dimensionConfig = (DefaultDimensionConfig) plotConfig.getDimensionConfig(dimensionSet.iterator().next()); DimensionConfigData dimensionConfigData = plotInstance.getPlotData().getDimensionConfigData(dimensionConfig); for (PlotDimension dimension : dimensionSet) { if (dimension == PlotDimension.COLOR) { colorProvider = dimensionConfigData.getColorProvider(); } else if (dimension == PlotDimension.SHAPE) { shapeProvider = dimensionConfigData.getShapeProvider(); } else if (dimension == PlotDimension.SIZE) { sizeProvider = dimensionConfigData.getSizeProvider(); } } // initialize size scale for legend ContinuousSizeProvider legendSizeProvider = null; if (sizeProvider != null) { double minScalingFactor = sizeProvider.getMinScalingFactor(); double maxScalingFactor = sizeProvider.getMaxScalingFactor(); double minLegendScalingFactor = MIN_LEGEND_ITEM_SCALING_FACTOR; double maxLegendScalingFactor = MAX_LEGEND_ITEM_SCALING_FACTOR; if (minScalingFactor > maxScalingFactor) { double tmp = minScalingFactor; minScalingFactor = maxScalingFactor; maxScalingFactor = tmp; minLegendScalingFactor = MAX_LEGEND_ITEM_SCALING_FACTOR; maxLegendScalingFactor = MIN_LEGEND_ITEM_SCALING_FACTOR; } legendSizeProvider = new ContinuousSizeProvider( minScalingFactor, maxScalingFactor, minLegendScalingFactor, maxLegendScalingFactor, false); } for (Double value : values) { // configure shape and stroke Shape shape = defaultShape; BasicStroke outlineStroke; Color outlineColor = new Color(0, 0, 0, 0); if (shapeProvider != null) { shape = shapeProvider.getShapeForCategory(value); outlineStroke = DEFAULT_OUTLINE_STROKE; outlineColor = defaultOutlineColor; } else { outlineStroke = new BasicStroke(); if (colorProvider != null) { shape = UNDEFINED_SHAPE; } else { shape = UNDEFINED_SHAPE_AND_COLOR; } } // configure fill paint Paint paint = UNDEFINED_COLOR_PAINT; if (colorProvider != null) { paint = colorProvider.getColorForValue(value); } double scalingFactor = 1; if (sizeProvider != null) { // scale shape according to sizeProvider scalingFactor = sizeProvider.getScalingFactorForValue(value); // scale shape to fit into legend scalingFactor = legendSizeProvider.getScalingFactorForValue(scalingFactor); AffineTransform transformation = new AffineTransform(); transformation.scale(scalingFactor, scalingFactor); shape = transformation.createTransformedShape(shape); } String label = dimensionConfigData.getStringForValue(value); if (label == null) { label = ""; } CustomLegendItem legendItem = new CustomLegendItem(label, null, null, null, shape, paint, outlineStroke, outlineColor); legendItemCollection.add(legendItem); } }
private void createDimensionConfigLegendItem( PlotInstance plotInstance, DefaultDimensionConfig dimensionConfig, Set<PlotDimension> dimensionSet, LegendItemCollection legendItemCollection) { PlotConfiguration plotConfiguration = plotInstance.getCurrentPlotConfigurationClone(); DimensionConfigData dimensionConfigData = plotInstance.getPlotData().getDimensionConfigData(dimensionConfig); if (dimensionConfig.isGrouping()) { // create legend entry based on the grouping if (dimensionConfig.isNominal()) { // create categorical legend --> one item for each category createCategoricalLegendItems( plotInstance, dimensionSet, legendItemCollection, dimensionConfigData.getDistinctValues()); } else if (dimensionConfig.isNumerical() || dimensionConfig.isDate()) { createDimensionTitleLegendItem(plotInstance, dimensionSet, legendItemCollection); // create one continuous legend item double minValue = dimensionConfigData.getMinValue(); double maxValue = dimensionConfigData.getMaxValue(); LegendItem legendItem = createContinuousLegendItem( plotInstance, dimensionSet, minValue, maxValue, dimensionConfig.isDate() ? dimensionConfig.getDateFormat() : null); if (legendItem != null) { legendItemCollection.add(legendItem); } } else { throw new RuntimeException( "unknown data type during legend creation - this should not happen"); } } else { // dimension config not grouping --> create legend item only, if there exists // at least one non-aggregated value source (otherwise the dimension config is // not used at all in the plot and thus we also don't need a legend item for it). boolean createLegend = false; for (ValueSource valueSource : plotConfiguration.getAllValueSources()) { if (!valueSource.isUsingDomainGrouping()) { createLegend = true; break; } } if (createLegend) { // create legend based on the attribute values on the dimension config if (dimensionConfig.isNominal()) { // create one legend item for each nominal value List<Double> values = dimensionConfigData.getDistinctValues(); createCategoricalLegendItems(plotInstance, dimensionSet, legendItemCollection, values); } else if (dimensionConfig.isNumerical() || dimensionConfig.isDate()) { createDimensionTitleLegendItem(plotInstance, dimensionSet, legendItemCollection); // create one continuous legend item for the value range double minValue = dimensionConfigData.getMinValue(); double maxValue = dimensionConfigData.getMaxValue(); LegendItem legendItem = createContinuousLegendItem( plotInstance, dimensionSet, minValue, maxValue, dimensionConfig.isDate() ? dimensionConfig.getDateFormat() : null); if (legendItem != null) { legendItemCollection.add(legendItem); } } else { throw new RuntimeException( "unknown data type during legend creation - this should not happen"); } } } }
/** @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("SHOW_SPECTRUM")) { CursorPosition pos = getCursorPosition(); if (pos != null) { SpectraVisualizerModule.showNewSpectrumWindow(pos.getDataFile(), pos.getScanNumber()); } } if (command.equals("SETUP_AXES")) { AxesSetupDialog dialog = new AxesSetupDialog(this, IDAPlot.getXYPlot()); dialog.setVisible(true); } if (command.equals("SHOW_DATA_POINTS")) { IDAPlot.switchDataPointsVisible(); } if (command.equals("SWITCH_TOOLTIPS")) { if (tooltipMode) { IDAPlot.showPeaksTooltips(false); toolBar.setTooltipButton(false); tooltipMode = false; } else { IDAPlot.showPeaksTooltips(true); toolBar.setTooltipButton(true); tooltipMode = true; } } if (command.equals("FIND_SPECTRA")) { // Parameters final DoubleParameter inputMZ = new DoubleParameter("Ion m/z", "m/z value of ion to search for."); final MZToleranceParameter inputMZTolerance = new MZToleranceParameter(); final DoubleParameter inputIntensity = new DoubleParameter( "Min. ion intensity", "Only ions with intensities above this value will be searched for."); final BooleanParameter inputNL = new BooleanParameter( "Neutral Loss", "If selected, the ion to be searched for will be a neutral loss ion.\nIn this case, only ions above the min. intensity will be examined.", false); final ComboParameter<Colors> inputColors = new ComboParameter<Colors>( "Color", "The color which the data points will be marked with.", Colors.values()); Parameter<?>[] parameters = new Parameter<?>[5]; parameters[0] = inputMZ; parameters[1] = inputMZTolerance; parameters[2] = inputIntensity; parameters[3] = inputNL; parameters[4] = inputColors; final ParameterSet parametersSearch = new SimpleParameterSet(parameters); ExitCode exitCode = parametersSearch.showSetupDialog(this, true); if (exitCode != ExitCode.OK) return; double searchMZ = parametersSearch.getParameter(inputMZ).getValue(); MZTolerance searchMZTolerance = parametersSearch.getParameter(inputMZTolerance).getValue(); double minIntensity = parametersSearch.getParameter(inputIntensity).getValue(); boolean neutralLoss = parametersSearch.getParameter(inputNL).getValue(); Color highligtColor = Color.red; ; if (parametersSearch.getParameter(inputColors).getValue().equals(Colors.green)) { highligtColor = Color.green; } if (parametersSearch.getParameter(inputColors).getValue().equals(Colors.blue)) { highligtColor = Color.blue; } // Find and highlight spectra with specific ion dataset.highlightSpectra( searchMZ, searchMZTolerance, minIntensity, neutralLoss, highligtColor); // Add legend entry LegendItemCollection chartLegend = IDAPlot.getXYPlot().getLegendItems(); chartLegend.add( new LegendItem( "Ion: " + searchMZ, "", "MS/MS spectra which contain the " + searchMZ + " ion\nTolerance: " + searchMZTolerance.toString() + "\nMin intensity: " + minIntensity, "", new Ellipse2D.Double(0, 0, 7, 7), highligtColor)); IDAPlot.getXYPlot().setFixedLegendItems(chartLegend); } }