Jfreechart - Chart Customization Problems

Asked

Viewed 1,486 times

6

I’m developing an application that has a dynamic graphic. I need to change the style of the graphic, but I’m not getting.

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

I’ve searched several tutorials on the internet and only managed to customize the color of the line. I always find some error or the code does not work.

Follows 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 markers and make the values that are in the graficoLinhas appear on these markers?

1 answer

6


I will start from what you posted in the question, then the two lines below create the graph and configure its background to the white color:

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 lines, dots, etc are plotted and that is why there are the other objects that we need to change.

As in the example we use a DefaultCategoryDataset, we will soon recover a CategoryPlot:

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

Recovered the object that represents the plotting area, we will also configure it to the white color, this way:

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

In the plotting area we have an object that is responsible for rendering the graph, an object of the type CategoryItemRenderer. How we’re using CategoryPlot, we can recover 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 get it back is basing it:

// 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 rendering documentation how you can do this.

The code line below makes the line of the graph 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 created a DecimalFormat very simple:

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

After we have created the formatting pattern we want for the item label, and we have configured this pattern, now just enable the display of the Labels on the chart. For this, just do the following:

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

Okay, we have our chart set up. To test, considering the dataset down 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:

Exemplo de Gráfico em Linhas

  • Thanks, @Bruno César. I’ll check if I can put it to work.

  • That’s it. It worked great. Thanks to your explanations, I was able to do and also change one or another detail. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.