Matthijs
Matthijs

Reputation: 155

How to combine a bar chart and a line chart in JFreeChart

I want to combine a line chart and a bar chart in a JFreeChart chart. What I've got so far is two lines. I have to change the renderer of one of the lines to a BarRenderer somehow. This is what I've got so far:

barDataset = new TimeSeriesCollection();
lineDataset = new TimeSeriesCollection();
totalDistanceSeries = new TimeSeries("Total Distance");
movingAverageSeries = new TimeSeries("Moving Average");
while (rs.next()) {
    myDate = rs.getDate("Date");
    d = new Day(myDate);
    totalDistance = rs.getDouble("TotaleAfstand");
    movingAverage = rs.getDouble("MovingAverage");
    totalDistanceSeries.add(d,totalDistance);
    movingAverageSeries.add(d,movingAverage);
}
barDataset.addSeries(totalDistanceSeries);
lineDataset.addSeries(movingAverageSeries);

String chartTitle = "Monthly Chart with Moving Average";
String xAxisLabel = "Date";
String yAxisLabel = "TotalDistance";

JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle,
        xAxisLabel, yAxisLabel, lineDataset);
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
renderer.setBaseShapesVisible(true);
XYPlot plot = (XYPlot) chart.getXYPlot();
plot.setDataset(1, barDataset);


chartPanel = new ChartPanel(chart);
chartPanel.setLocation(10,60);
chartPanel.setSize(1850, 900);
add(chartPanel);

Does someone know how to do this?

Upvotes: 0

Views: 170

Answers (1)

Matthijs
Matthijs

Reputation: 155

I needed a XYBarRenderer instead of just a BarRenderer. This is the code I added below plot.setDataset(1, barDataset); :

XYBarRenderer renderer2=new XYBarRenderer(0.20);
plot.setRenderer(1, renderer2);

Upvotes: 1

Related Questions