Java Code Examples for org.jfree.chart.JFreeChart

The following examples show how to use org.jfree.chart.JFreeChart. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: astor   Source File: AreaRendererTests.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * A check for the datasetIndex and seriesIndex fields in the LegendItem
 * returned by the getLegendItem() method.
 */
public void testGetLegendItemSeriesIndex() {
    DefaultCategoryDataset dataset0 = new DefaultCategoryDataset();
    dataset0.addValue(21.0, "R1", "C1");
    dataset0.addValue(22.0, "R2", "C1");
    DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
    dataset1.addValue(23.0, "R3", "C1");
    dataset1.addValue(24.0, "R4", "C1");
    dataset1.addValue(25.0, "R5", "C1");
    AreaRenderer r = new AreaRenderer();
    CategoryPlot plot = new CategoryPlot(dataset0, new CategoryAxis("x"),
            new NumberAxis("y"), r);
    plot.setDataset(1, dataset1);
    /*JFreeChart chart =*/ new JFreeChart(plot);
    LegendItem li = r.getLegendItem(1, 2);
    assertEquals("R5", li.getLabel());
    assertEquals(1, li.getDatasetIndex());
    assertEquals(2, li.getSeriesIndex());
}
 
Example 2
protected ChartPanel createAgentNumberPanel(final Currency currency, final Class<? extends Agent> agentType) {
	final TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

	timeSeriesCollection.addSeries(ApplicationContext.getInstance().getModelRegistry()
			.getNationalEconomyModel(currency).numberOfAgentsModels.get(agentType).getTimeSeries());

	// in case of households
	if (Household.class.isAssignableFrom(agentType)) {
		// show retired households
		timeSeriesCollection.addSeries(ApplicationContext.getInstance().getModelRegistry()
				.getNationalEconomyModel(currency).householdsModel.retiredModel.getTimeSeries());
	}

	final JFreeChart chart = ChartFactory.createTimeSeriesChart("# " + agentType.getSimpleName() + " Agents",
			"Date", "# Agents", timeSeriesCollection, true, true, false);
	configureChart(chart);
	return new ChartPanel(chart);
}
 
Example 3
Source Project: ECG-Viewer   Source File: LogAxisTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks that the auto-range for the range axis on an XYPlot is
 * working as expected.
 */
@Test
public void testXYAutoRange2() {
    XYSeries series = new XYSeries("Series 1");
    series.add(1.0, 1.0);
    series.add(2.0, 2.0);
    series.add(3.0, 3.0);
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y",
            dataset);
    XYPlot plot = (XYPlot) chart.getPlot();
    LogAxis axis = new LogAxis("Log(Y)");
    plot.setRangeAxis(axis);
    assertEquals(0.9465508226401592, axis.getLowerBound(), EPSILON);
    assertEquals(3.1694019256486126, axis.getUpperBound(), EPSILON);
}
 
Example 4
Source Project: nmonvisualizer   Source File: LineChartBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the X axis to display time relative to the given start time.
 */
// for relative time, format the x axis differently
// the data _does not_ change
public static void setRelativeAxis(JFreeChart chart, long startTime) {
    if (chart != null) {
        RelativeDateFormat format = new RelativeDateFormat(startTime);
        // : separators
        format.setHourSuffix(":");
        format.setMinuteSuffix(":");
        format.setSecondSuffix("");

        // zero pad minutes and seconds
        DecimalFormat padded = new DecimalFormat("00");
        format.setMinuteFormatter(padded);
        format.setSecondFormatter(padded);

        XYPlot plot = chart.getXYPlot();

        ((DateAxis) plot.getDomainAxis()).setDateFormatOverride(format);
    }
}
 
Example 5
/**
 * Draws a chart where the dataset contains a null median value.
 */
@Test
public void testDrawWithNullMedian() {
    boolean success;
    try {
        DefaultBoxAndWhiskerCategoryDataset dataset
                = new DefaultBoxAndWhiskerCategoryDataset();
        dataset.add(new BoxAndWhiskerItem(new Double(1.0), null,
                new Double(0.0), new Double(4.0), new Double(0.5),
                new Double(4.5), new Double(-0.5), new Double(5.5),
                null), "S1", "C1");
        CategoryPlot plot = new CategoryPlot(dataset,
                new CategoryAxis("Category"), new NumberAxis("Value"),
                new BoxAndWhiskerRenderer());
        ChartRenderingInfo info = new ChartRenderingInfo();
        JFreeChart chart = new JFreeChart(plot);
        /* BufferedImage image = */ chart.createBufferedImage(300, 200,
                info);
        success = true;
    }
    catch (Exception e) {
        success = false;
    }
    assertTrue(success);
}
 
Example 6
@Override
@Transactional( readOnly = true )
public JFreeChart getJFreeOrganisationUnitChart( Indicator indicator, OrganisationUnit parent, boolean title,
    I18nFormat format )
{
    List<Period> periods = periodService.reloadPeriods(
        new RelativePeriods().setThisYear( true ).getRelativePeriods( format, true ) );

    Chart chart = new Chart();

    if ( title )
    {
        chart.setName( indicator.getName() );
    }

    chart.setType( ChartType.COLUMN );
    chart.setDimensions( DimensionalObject.DATA_X_DIM_ID, DimensionalObject.ORGUNIT_DIM_ID, DimensionalObject.PERIOD_DIM_ID );
    chart.setHideLegend( true );
    chart.addDataDimensionItem( indicator );
    chart.setPeriods( periods );
    chart.setOrganisationUnits( parent.getSortedChildren() );
    chart.setHideSubtitle( title );
    chart.setFormat( format );

    return getJFreeChart( chart );
}
 
Example 7
/**
 *
 */
protected JFreeChart createAreaChart() throws JRException 
{
	ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
	JFreeChart jfreeChart = 
		ChartFactory.createAreaChart( 
			evaluateTextExpression(getChart().getTitleExpression()),
			evaluateTextExpression(((JRAreaPlot)getPlot()).getCategoryAxisLabelExpression()),
			evaluateTextExpression(((JRAreaPlot)getPlot()).getValueAxisLabelExpression()),
			(CategoryDataset)getDataset(),
			getPlot().getOrientationValue().getOrientation(),
			isShowLegend(),
			true,
			false);

	configureChart(jfreeChart, getPlot());
	JRAreaPlot areaPlot = (JRAreaPlot)getPlot();
	// Handle the axis formating for the category axis
	configureAxis(((CategoryPlot)jfreeChart.getPlot()).getDomainAxis(), areaPlot.getCategoryAxisLabelFont(),
			areaPlot.getCategoryAxisLabelColor(), areaPlot.getCategoryAxisTickLabelFont(),
			areaPlot.getCategoryAxisTickLabelColor(), areaPlot.getCategoryAxisTickLabelMask(), areaPlot.getCategoryAxisVerticalTickLabels(),
			areaPlot.getOwnCategoryAxisLineColor(), getDomainAxisSettings(),
			(Comparable<?>)evaluateExpression(areaPlot.getDomainAxisMinValueExpression()), 
			(Comparable<?>)evaluateExpression(areaPlot.getDomainAxisMaxValueExpression())
			);
	// Handle the axis formating for the value axis
	configureAxis(((CategoryPlot)jfreeChart.getPlot()).getRangeAxis(), areaPlot.getValueAxisLabelFont(),
			areaPlot.getValueAxisLabelColor(), areaPlot.getValueAxisTickLabelFont(),
			areaPlot.getValueAxisTickLabelColor(), areaPlot.getValueAxisTickLabelMask(), areaPlot.getValueAxisVerticalTickLabels(),
			areaPlot.getOwnValueAxisLineColor(), getRangeAxisSettings(),
			(Comparable<?>)evaluateExpression(areaPlot.getRangeAxisMinValueExpression()), 
			(Comparable<?>)evaluateExpression(areaPlot.getRangeAxisMaxValueExpression())
	);
	return jfreeChart;
}
 
Example 8
Source Project: SPIM_Registration   Source File: GraphFrame.java    License: GNU General Public License v2.0 6 votes vote down vote up
public GraphFrame( final JFreeChart chart, final int referenceTimePoint, final boolean enableReferenceTimePoint, final List<FileOpenMenuEntry> extraMenuItems, final ArrayList< RegistrationStatistics > data )
{
	super();
	
	this.referenceTimePoint = referenceTimePoint;
	this.enableReferenceTimePoint = enableReferenceTimePoint;

	mainPanel = new JPanel();
	mainPanel.setLayout( new BorderLayout() );

	updateWithNewChart( chart, true, extraMenuItems, data );

	JPanel buttonsPanel = new JPanel();
	mainPanel.add( buttonsPanel, BorderLayout.SOUTH );

	setContentPane( mainPanel );
	validate();
	GUI.center( this );
}
 
Example 9
Source Project: SIMVA-SoS   Source File: XYPlotTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A test for drawing range grid lines when there is no primary renderer.
 * In 1.0.4, this is throwing a NullPointerException.
 */
@Test
public void testDrawRangeGridlines() {
    DefaultXYDataset dataset = new DefaultXYDataset();
    JFreeChart chart = ChartFactory.createXYLineChart("Title", "X", "Y",
            dataset, PlotOrientation.VERTICAL, true, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setRenderer(null);
    try {
        BufferedImage image = new BufferedImage(200 , 100,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
        g2.dispose();
    }
    catch (Exception e) {
        fail("No exception should be thrown.");
    }
}
 
Example 10
/**
 * Check that only one chart change event is generated by a change to a
 * subplot.
 */
@Test
public void testNotification() {
    CombinedDomainXYPlot plot = createPlot();
    JFreeChart chart = new JFreeChart(plot);
    chart.addChangeListener(this);
    XYPlot subplot1 = (XYPlot) plot.getSubplots().get(0);
    NumberAxis yAxis = (NumberAxis) subplot1.getRangeAxis();
    yAxis.setAutoRangeIncludesZero(!yAxis.getAutoRangeIncludesZero());
    assertEquals(1, this.events.size());

    // a redraw should NOT trigger another change event
    BufferedImage image = new BufferedImage(200, 100,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    this.events.clear();
    chart.draw(g2, new Rectangle2D.Double(0.0, 0.0, 200.0, 100.0));
    assertTrue(this.events.isEmpty());
}
 
Example 11
/**
 * Draws the chart with a <code>null</code> info object to make sure that
 * no exceptions are thrown (particularly by code in the renderer).
 */
@Test
public void testDrawWithNullInfo() {
    try {
        double[][] starts = new double[][] {{0.1, 0.2, 0.3},
                {0.3, 0.4, 0.5}};
        double[][] ends = new double[][] {{0.5, 0.6, 0.7}, {0.7, 0.8, 0.9}};
        DefaultIntervalCategoryDataset dataset
                = new DefaultIntervalCategoryDataset(starts, ends);
        IntervalBarRenderer renderer = new IntervalBarRenderer();
        CategoryPlot plot = new CategoryPlot(dataset,
                new CategoryAxis("Category"), new NumberAxis("Value"),
                renderer);
        JFreeChart chart = new JFreeChart(plot);
        /* BufferedImage image = */ chart.createBufferedImage(300, 200,
                null);
    }
    catch (NullPointerException e) {
        fail("No exception should be thrown.");
    }
}
 
Example 12
Source Project: SIMVA-SoS   Source File: StandardXYItemRendererTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A check to ensure that an item that falls outside the plot's data area
 * does NOT generate an item entity.
 */
@Test
public void testNoDisplayedItem() {
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries s1 = new XYSeries("S1");
    s1.add(10.0, 10.0);
    dataset.addSeries(s1);
    JFreeChart chart = ChartFactory.createXYLineChart("Title", "X", "Y",
            dataset, PlotOrientation.VERTICAL, false, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setRenderer(new StandardXYItemRenderer());
    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setRange(0.0, 5.0);
    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setRange(0.0, 5.0);
    BufferedImage image = new BufferedImage(200 , 100,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    ChartRenderingInfo info = new ChartRenderingInfo();
    chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, info);
    g2.dispose();
    EntityCollection ec = info.getEntityCollection();
    assertFalse(TestUtilities.containsInstanceOf(ec.getEntities(),
            XYItemEntity.class));
}
 
Example 13
Source Project: ECG-Viewer   Source File: AreaRendererTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * A check for the datasetIndex and seriesIndex fields in the LegendItem
 * returned by the getLegendItem() method.
 */
@Test
public void testGetLegendItemSeriesIndex() {
    DefaultCategoryDataset dataset0 = new DefaultCategoryDataset();
    dataset0.addValue(21.0, "R1", "C1");
    dataset0.addValue(22.0, "R2", "C1");
    DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
    dataset1.addValue(23.0, "R3", "C1");
    dataset1.addValue(24.0, "R4", "C1");
    dataset1.addValue(25.0, "R5", "C1");
    AreaRenderer r = new AreaRenderer();
    CategoryPlot plot = new CategoryPlot(dataset0, new CategoryAxis("x"),
            new NumberAxis("y"), r);
    plot.setDataset(1, dataset1);
    /*JFreeChart chart =*/ new JFreeChart(plot);
    LegendItem li = r.getLegendItem(1, 2);
    assertEquals("R5", li.getLabel());
    assertEquals(1, li.getDatasetIndex());
    assertEquals(2, li.getSeriesIndex());
}
 
Example 14
Source Project: buffer_bci   Source File: MultiplePiePlot.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new plot.
 *
 * @param dataset  the dataset (<code>null</code> permitted).
 */
public MultiplePiePlot(CategoryDataset dataset) {
    super();
    setDataset(dataset);
    PiePlot piePlot = new PiePlot(null);
    piePlot.setIgnoreNullValues(true);
    this.pieChart = new JFreeChart(piePlot);
    this.pieChart.removeLegend();
    this.dataExtractOrder = TableOrder.BY_COLUMN;
    this.pieChart.setBackgroundPaint(null);
    TextTitle seriesTitle = new TextTitle("Series Title",
            new Font("SansSerif", Font.BOLD, 12));
    seriesTitle.setPosition(RectangleEdge.BOTTOM);
    this.pieChart.setTitle(seriesTitle);
    this.aggregatedItemsKey = "Other";
    this.aggregatedItemsPaint = Color.lightGray;
    this.sectionPaints = new HashMap();
    this.legendItemShape = new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0);
}
 
Example 15
/**
 * Creates the histogram chart.
 *
 * @param exampleSet
 * @return
 */
private JFreeChart createHistogramChart(ExampleSet exampleSet) {
	JFreeChart chart = ChartFactory.createHistogram(null, null, null, createHistogramDataset(exampleSet),
			PlotOrientation.VERTICAL, false, false, false);
	AbstractAttributeStatisticsModel.setDefaultChartFonts(chart);
	chart.setBackgroundPaint(null);
	chart.setBackgroundImageAlpha(0.0f);

	XYPlot plot = (XYPlot) chart.getPlot();
	plot.setRangeGridlinesVisible(false);
	plot.setDomainGridlinesVisible(false);
	plot.setOutlineVisible(false);
	plot.setRangeZeroBaselineVisible(false);
	plot.setDomainZeroBaselineVisible(false);
	plot.setBackgroundPaint(COLOR_INVISIBLE);
	plot.setBackgroundImageAlpha(0.0f);

	XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();
	renderer.setSeriesPaint(0, AttributeGuiTools.getColorForValueType(Ontology.NUMERICAL));
	renderer.setBarPainter(new StandardXYBarPainter());
	renderer.setDrawBarOutline(true);
	renderer.setShadowVisible(false);

	return chart;
}
 
Example 16
public static byte[] getChartAsPngByteArray( JFreeChart jFreeChart, int width, int height )
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try
    {
        org.jfree.chart.ChartUtils.writeChartAsPNG( out, jFreeChart, width, height );
        out.flush();

        return out.toByteArray();
    }
    catch ( IOException ex )
    {
        throw new UncheckedIOException( ex );
    }
}
 
Example 17
Source Project: openstock   Source File: CategoryPlotTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * A test for bug 1654215 (where a renderer is added to the plot without
 * a corresponding dataset and it throws an exception at drawing time).
 */
@Test
public void test1654215() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    JFreeChart chart = ChartFactory.createLineChart("Title", "X", "Y",
            dataset, PlotOrientation.VERTICAL, true, false, false);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setRenderer(1, new LineAndShapeRenderer());
    try {
        BufferedImage image = new BufferedImage(200 , 100,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
        g2.dispose();
    }
    catch (Exception e) {
        fail("No exception should be thrown.");
    }
}
 
Example 18
Source Project: qpid-broker-j   Source File: TimeSeriesLineChartBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JFreeChart createChartImpl(String title, String xAxisTitle,
        String yAxisTitle, final Dataset dataset, PlotOrientation plotOrientation,
        boolean showLegend, boolean showToolTips, boolean showUrls)
{
    JFreeChart chart = ChartFactory.createTimeSeriesChart(
            title,
            xAxisTitle,
            yAxisTitle,
            (XYDataset)dataset,
            showLegend,
            showToolTips,
            showUrls);

    return chart;
}
 
Example 19
@Override
public void chartMouseMoved(ChartMouseEventFX event) {
    Rectangle2D dataArea = this.chartViewer.getCanvas().getRenderingInfo().getPlotInfo().getDataArea();
    JFreeChart chart = event.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    ValueAxis xAxis = plot.getDomainAxis();
    double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea, 
            RectangleEdge.BOTTOM);
    // make the crosshairs disappear if the mouse is out of range
    if (!xAxis.getRange().contains(x)) { 
        x = Double.NaN;                  
    }
    double y = DatasetUtils.findYValue(plot.getDataset(), 0, x);
    this.xCrosshair.setValue(x);
    this.yCrosshair.setValue(y);
}
 
Example 20
/**
 * Two objects that are equal are required to return the same hashCode.
 */
@Test
public void testHashCode() {
    Image image = JFreeChart.INFO.getLogo();
    XYImageAnnotation a1 = new XYImageAnnotation(10.0, 20.0, image);
    XYImageAnnotation a2 = new XYImageAnnotation(10.0, 20.0, image);
    assertTrue(a1.equals(a2));
    int h1 = a1.hashCode();
    int h2 = a2.hashCode();
    assertEquals(h1, h2);
}
 
Example 21
Source Project: mzmine3   Source File: ChartExportUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Paints a chart with scaling options
 *
 * @param chart
 * @param info
 * @param out
 * @param width
 * @param height
 * @param resolution
 * @return BufferedImage of a given chart with scaling to resolution
 * @throws IOException
 */
private static BufferedImage paintScaledChartToBufferedImage(JFreeChart chart,
    ChartRenderingInfo info, OutputStream out, int width, int height, int resolution,
    int bufferedIType) throws IOException {
  Args.nullNotPermitted(out, "out");
  Args.nullNotPermitted(chart, "chart");

  double scaleX = resolution / 72.0;
  double scaleY = resolution / 72.0;

  double desiredWidth = width * scaleX;
  double desiredHeight = height * scaleY;
  double defaultWidth = width;
  double defaultHeight = height;
  boolean scale = false;

  // get desired width and height from somewhere then...
  if ((scaleX != 1) || (scaleY != 1)) {
    scale = true;
  }

  BufferedImage image = new BufferedImage((int) desiredWidth, (int) desiredHeight, bufferedIType);
  Graphics2D g2 = image.createGraphics();

  if (scale) {
    AffineTransform saved = g2.getTransform();
    g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));
    chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight), info);
    g2.setTransform(saved);
    g2.dispose();
  } else {
    chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight), info);
  }
  return image;
}
 
Example 22
Source Project: qpid-broker-j   Source File: BaseChartBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void configureYAxisBounds(final ChartingDefinition chartingDefinition, final JFreeChart chart)
{
    if (chart.getPlot() != null && chart.getPlot() instanceof XYPlot)
    {
        ValueAxis rangeAxis = chart.getXYPlot().getRangeAxis();
        if (chartingDefinition.getYAxisLowerBound() != null)
        {
            rangeAxis.setLowerBound(chartingDefinition.getYAxisLowerBound());
        }
        if (chartingDefinition.getYAxisUpperBound() != null)
        {
            rangeAxis.setUpperBound(chartingDefinition.getYAxisUpperBound());
        }
    }
}
 
Example 23
Source Project: SIMVA-SoS   Source File: LogAxisTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A simple test for the auto-range calculation looking at a
 * LogAxis used as the range axis for a CategoryPlot.
 */
@Test
public void testAutoRange1() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(100.0, "Row 1", "Column 1");
    dataset.setValue(200.0, "Row 1", "Column 2");
    JFreeChart chart = ChartFactory.createBarChart("Test", "Categories",
            "Value", dataset);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    LogAxis axis = new LogAxis("Log(Y)");
    plot.setRangeAxis(axis);
    assertEquals(0.0, axis.getLowerBound(), EPSILON);
    assertEquals(2.6066426411261268E7, axis.getUpperBound(), EPSILON);
}
 
Example 24
@Override
public void start(Stage stage) throws Exception {
  XYDataset dataset = createDataset();
  JFreeChart chart = ChartFactory.createXYLineChart("Random", "i", "r", createDataset());
  EChartViewer canvas = new EChartViewer(chart);
  StackPane stackPane = new StackPane();
  stackPane.getChildren().add(canvas);
  stage.setScene(new Scene(stackPane));
  stage.setTitle("Chart gesture demo");
  stage.setWidth(700);
  stage.setHeight(390);
  stage.show();
}
 
Example 25
Source Project: old-mzmine3   Source File: ChartExportUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void writeChartToEMF(JFreeChart chart, int width, int height, File name)
    throws IOException {
  try {
    VectorGraphics g = new EMFGraphics2D(name, new Dimension(width, height));
    g.startExport();
    Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);
    chart.draw((Graphics2D) g, rectangle2d);
    g.endExport();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    throw e;
  }
}
 
Example 26
private JFreeChart getMultiplePieChart( final Visualization visualization, CategoryDataset[] dataSets )
{
    JFreeChart multiplePieChart = ChartFactory.createMultiplePieChart( visualization.getName(), dataSets[0], TableOrder.BY_ROW,
        !visualization.isHideLegend(), false, false );

    setBasicConfig( multiplePieChart, visualization );

    if ( multiplePieChart.getLegend() != null )
    {
        multiplePieChart.getLegend().setItemFont( SUB_TITLE_FONT );
    }

    MultiplePiePlot multiplePiePlot = (MultiplePiePlot) multiplePieChart.getPlot();
    JFreeChart pieChart = multiplePiePlot.getPieChart();
    pieChart.setBackgroundPaint( DEFAULT_BACKGROUND_COLOR );
    pieChart.getTitle().setFont( SUB_TITLE_FONT );

    PiePlot piePlot = (PiePlot) pieChart.getPlot();
    piePlot.setBackgroundPaint( DEFAULT_BACKGROUND_COLOR );
    piePlot.setOutlinePaint( DEFAULT_BACKGROUND_COLOR );
    piePlot.setLabelFont( LABEL_FONT );
    piePlot.setLabelGenerator( new StandardPieSectionLabelGenerator( "{2}" ) );
    piePlot.setSimpleLabels( true );
    piePlot.setIgnoreZeroValues( true );
    piePlot.setIgnoreNullValues( true );
    piePlot.setShadowXOffset( 0d );
    piePlot.setShadowYOffset( 0d );

    for ( int i = 0; i < dataSets[0].getColumnCount(); i++ )
    {
        piePlot.setSectionPaint( dataSets[0].getColumnKey( i ), COLORS[(i % COLORS.length)] );
    }

    return multiplePieChart;
}
 
Example 27
protected void configureChart( final JFreeChart chart ) {
  super.configureChart( chart );

  final CategoryPlot cpl = chart.getCategoryPlot();
  final CategoryItemRenderer renderer = cpl.getRenderer();
  renderer.setStroke( translateLineStyle( lineWidth, lineStyle ) );
  if ( renderer instanceof LineAndShapeRenderer ) {
    final LineAndShapeRenderer shapeRenderer = (LineAndShapeRenderer) renderer;
    shapeRenderer.setShapesVisible( isMarkersVisible() );
    shapeRenderer.setBaseShapesFilled( isMarkersVisible() );
  }

}
 
Example 28
/**
 * Creates a chart.
 *
 * @param dataset  a dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(XYDataset dataset) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart(
        "Legal & General Unit Trust Prices",  // title
        "Date",             // x-axis label
        "Price Per Unit",   // y-axis label
        dataset,            // data
        true,               // create legend?
        true,               // generate tooltips?
        false               // generate URLs?
    );

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesVisible(true);
        renderer.setBaseShapesFilled(true);
        renderer.setDrawSeriesLineAsPath(true);
    }

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));

    return chart;

}
 
Example 29
public LinkAndBrushChartPanel(JFreeChart chart, int defaultWidth, int defaultHeigth, int minDrawWidth,
		int minDrawHeigth, boolean zoomOnLinkAndBrush) {
	super(chart, defaultWidth, defaultHeigth, minDrawWidth, minDrawHeigth, DEFAULT_MAXIMUM_DRAW_WIDTH,
			DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, false,  // copy
			false,  // properties
			false,  // save
			false,  // print
			false,  // zoom
			true);   // tooltips

	this.zoomOnLinkAndBrushSelection = zoomOnLinkAndBrush;
	setInitialDelay(200);

	setMouseWheelEnabled(false);
}
 
Example 30
Source Project: heroic   Source File: RenderUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static JFreeChart buildChart(
    final String title, final XYDataset lineAndShape, final XYDataset interval,
    final XYItemRenderer lineAndShapeRenderer, final XYItemRenderer intervalRenderer
) {
    final ValueAxis timeAxis = new DateAxis();
    timeAxis.setLowerMargin(0.02);
    timeAxis.setUpperMargin(0.02);

    final NumberAxis valueAxis = new NumberAxis();
    valueAxis.setAutoRangeIncludesZero(false);

    final XYPlot plot = new XYPlot();

    plot.setDomainAxis(0, timeAxis);
    plot.setRangeAxis(0, valueAxis);

    plot.setDataset(0, lineAndShape);
    plot.setRenderer(0, lineAndShapeRenderer);

    plot.setDomainAxis(1, timeAxis);
    plot.setRangeAxis(1, valueAxis);

    plot.setDataset(1, interval);
    plot.setRenderer(1, intervalRenderer);

    return new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, false);
}