JFreeChart - Problems customizing chart

6

I'm developing an application that has a PivotChart. I need to change the style of the chart, but I can not.

I need it to have white background, blue line with square markers and have the values on each marker.

I have already searched for several tutorials on the internet and only managed to customize the color of the line. I always encounter an error or the code does not work.

Follow my code:

public void montaImagem(ActionMapping mapping, ActionForm pform, HttpServletRequest request, HttpServletResponse response) throws SQLException {
    DefaultCategoryDataset graficoLinhas = new DefaultCategoryDataset();
    // * Crio o dataSet graficoLinhas a partir da resposta do banco *
    try{
        JFreeChart objetoGrafico = ChartFactory.createLineChart("Taxa(%)",
                "Meses", //linha X
                "", //linha Y
                graficoLinhas, //gráfico gerado acima
                PlotOrientation.VERTICAL, //orientação do gráfico
                true, 
                true,
                false);

        //Setando BG para BRANCO - único comando customizador que parece funcionar.
        objetoGrafico.setBackgroundPaint(Color.WHITE); 
        // * A partir daqui, gero a imagem de resposta, o código funciona como deveria *

How do I set the line to Blue, insert the markers and make the values that are in graficoLinhas appear on these markers?

    
asked by anonymous 30.04.2015 / 21:59

1 answer

6

I'll start from what you posted in the question, so the two lines below create the graph and set the background to white:

final JFreeChart chart = ChartFactory.createLineChart("Taxa (%)", "Meses", "", dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(Color.WHITE);

Started the graph, we have to recover the Plot , which is the body of the graph, where the lines, points, etc are plotted and that is why the other objects that we need to change are.

As in the example we used a DefaultCategoryDataset , we'll soon retrieve a CategoryPlot :

// recupera o ploter, estamos recuparando um "CategoryPlot" devido ao dataset usado
final CategoryPlot plot = chart.getCategoryPlot();

Retrieving the object representing the plot area, let's also set it to white, like this:

// torna o fundo da área de plotagem do gráfico branda
plot.setBackgroundPaint(Color.WHITE);

In the plot area we have an object that is responsible for rendering the graph, an object of type CategoryItemRenderer . Since we're using CategoryPlot , we can retrieve a LineAndShapeRenderer , according to the documentation:

  

A renderer that draws shapes for each data item, and lines between data items (for use with the CategoryPlot class).

So, to recover it is basic this:

// recupera o renderer que represneta a linha plotada
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();

With the line below we make the square markers visible.

// tornando os marcadores quadrados visíveis
renderer.setBaseShapesVisible(true);

To customize them in other ways, look at the renderer documentation how you can do this.

The line of code below makes the chart line blue. The square marker, by default, follows this same color:

// altera a cor da linha
renderer.setSeriesPaint(0, Color.BLUE);

Finally, let's create a formatting pattern for the label. StandardCategoryItemLabelGenerator receives as second argument a NumberFormat , I have created a DecimalFormat simple even:

// cria o de formatação para o label do item
final DecimalFormat format = new DecimalFormat("#0.##");
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", format));

Once we have created the formatting pattern we want for the item label, and if we have set this pattern, now we just have to enable the display of the labels on the chart. To do this, simply do the following:

// torna o label visível para cada item
renderer.setBaseItemLabelsVisible(true);

Okay, we already have our chart set up. To test, considering the dataset below:

final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(15.7, "taxa", "JAN");
dataset.addValue(21.2, "taxa", "FEV");
dataset.addValue(20.7, "taxa", "MAR");
dataset.addValue(18, "taxa", "ABR");
dataset.addValue(22.9, "taxa", "MAI");
dataset.addValue(13.4, "taxa", "JUN");
dataset.addValue(17.8, "taxa", "JUL");
dataset.addValue(9.7, "taxa", "AGO");
dataset.addValue(14.3, "taxa", "SET");
dataset.addValue(13.8, "taxa", "OUT");
dataset.addValue(12.4, "taxa", "NOV");
dataset.addValue(11.7, "taxa", "DEZ");

and the customizations mentioned above, we get this result:

    
01.05.2015 / 04:58