steelmonkey
steelmonkey

Reputation: 459

Create Fatter Candlesticks in JFreeChart

I'm developing an app that displays daily financial data, and have chosen to use JFreeChart. I was able to learn how to create a candlestick chart, but my problem lies in customization.

You see, what I'm aiming for is more along the lines of

this

While, so far all I've been able to manage is

this.

No matter how far I zoom in, the candlesticks do not increase in width.

I'm fairly certain that somehow the thin candlesticks have something to do with being bound to a certain time range.. I've tried to remedy that but am not sure what I'm doing wrong here.

SSCE

    public void showStockHistory(OHLCDataset dataset, String stockName) {
    JFreeChart candleChart = ChartFactory.createCandlestickChart("History of " + stockName, "Date", "Stock Points", dataset, true);

    XYPlot plot = candleChart.getXYPlot();
        plot.setDomainPannable(true);
        plot.setRangePannable(true);

    ValueAxis domain = plot.getDomainAxis();
        domain.setAutoRange(true);

    NumberAxis range = (NumberAxis)plot.getRangeAxis();
        range.setUpperMargin(0.0D);
        range.setLowerMargin(0.0D);
        range.setAutoRange(true);
        range.setAutoRangeIncludesZero(false);

    ChartPanel chartPanel = new ChartPanel(candleChart);
        chartPanel.setMouseWheelEnabled(true);
        chartPanel.setMouseZoomable(true);

    getViewport().add(chartPanel);
    }

Upvotes: 1

Views: 1051

Answers (1)

steelmonkey
steelmonkey

Reputation: 459

Although my given example seems to have to no differing method calls from the demo in the first picture's code above, it nevertheless only shows thin candlesticks. I assume this to be some kind of bug.

However, I was able to rectify the issue as follows:

  1. getting the renderer for the chart,

  2. casting it to a type of CandlestickRenderer, and

  3. setting its setAutoWidthMethod() method to CandlestickRenderer.WIDTHMETHOD_SMALLEST.

This is how you do it:

JFreeChart candleChart = ChartFactory.createCandlestickChart(
    "History of " + stockName, "Date", "Stock Points", dataset, true);
XYPlot plot = candleChart.getXYPlot();
CandlestickRenderer renderer = (CandlestickRenderer) plot.getRenderer();
renderer.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);

Upvotes: 3

Related Questions