JFreeChart Link Axes

2019-07-19 11:02发布

问题:

I have created a Frame with two independent separate JFree charts (held in a 2x1 Grid layout). The top chart shows a Canlestick chart, the bottom a time series plot. What I would like to do is link the displayed X-Axis of both charts so that when I zoom in on one chart the other chart zooms to the corresponding time period.

Is this possible? If so could you give me an example

回答1:

What you need is called CombinedDomainXYPlot. Instead of creating independent JFreeChart objects you will need to create one Combined plot and put there all plots needs to be linked.



回答2:

Add a listener to both charts using JFreeChart#addChangeListener() and synchronize the DomainAxis inside ChartChangeListener#chartChanged() you will need some way of preventing an infinite loop.



回答3:

I did a similar thing with multiple charts in an application I am writing... I simply set the DomainAxis for one chart to the DomainAxis from another chart, i.e. they both refer to the single DomainAxis.

JFreeChart chart1 = ChartFactory.createXYLineChart();
JFreeChart chart2 = ChartFactory.createXYLineChart();
XYPlot plot1 = chart1.getXYPlot();
XYPlot plot2 = chart2.getXYPlot();

plot2.setDomainAxis(plot1.getDomainAxis());

Now when I zoom in chart1, both charts show the same zoomed Domain.

Note, I ensure that the domain's are the same size/length in my charts by data mangling outside the charting.



回答4:

using CombinedDomainXYPlot as demonstrated by JFreeChartCombinedXYPlotDemo1 is the way to go.

If you use the alternate solution on this page ("simply set the DomainAxis for one chart to the DomainAxis from another chart") this will only work if points on both charts have the same start and end xAxis values (and perhaps other problems also).