JFreeChart Bar Chart Production

浪尽此生 提交于 2019-12-02 01:15:56

I guess you are doing a small mistake, that is with in for loop for each iteration of loop you are creating a new DefaultCategoryDataset instance. So each time each item is added to a separate DefaultCategoryDataset object and the final DefaultCategoryDataset instance having the last value is utilized to create the chart, that is the only reason you are getting only last value in your chart.

Solution is create DefaultCategoryDataset object outside and before the for loop only once like:

DefaultCategoryDataset barChartDataset = new DefaultCategoryDataset();

for (int l = 0; l < data.length; l++) {

       // barChartDataset.setValue(new Double(data[l]), "Scores", stu);
       barChartDataset.addValue(new Double(data[l]), "Scores", stu);
       System.out.println(data[l]);
    }

    JFreeChart barChart = ChartFactory.createBarChart3D("Summary", "Name", "Scores", barChartDataset, PlotOrientation.VERTICAL, false, true, false);

Here is the code snippet I have in one of my application and it is working fine:

 DefaultCategoryDataset dataset= new DefaultCategoryDataset();
  // Get today as a Calendar.... 
  Calendar today = Calendar.getInstance();

 for(int i=0; i<15 ;i++)
  {  
   //get util.Date class object for today date.....
   java.util.Date today_date=new java.util.Date(today.getTimeInMillis());

   //convert date in string format to display on chart.....
    String today_string_date = new SimpleDateFormat("dd/MM/yy").format(today_date);

    // set values to DefaultCategoryDataset to display on chart...
    dataset.setValue(rs1.getInt("login_count"),"Login Frequency", today_string_date);
    today.add(Calendar.DATE, -1);

  }// for closing...

JFreeChart chart = ChartFactory.createBarChart3D("ISIS:Overall login history for last 15 days", "Date -->", "No  of  user(s)  login  per  day -->", dataset, PlotOrientation.VERTICAL, true, true, false);

 CategoryPlot p = chart.getCategoryPlot(); 
 NumberAxis rangeAxis = (NumberAxis) p.getRangeAxis();

 rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
 BarRenderer renderer = (BarRenderer) p.getRenderer();
 DecimalFormat decimalformat1 = new DecimalFormat("##");
 renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", decimalformat1));
 renderer.setItemLabelsVisible(true);

ChartUtilities.saveChartAsPNG(new File(filePath +"/chart1.png"), chart ,1250, 400);

I hope it will solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!