`
13146489
  • 浏览: 251377 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

jfreechart 自定义饼图颜色

    博客分类:
  • J2EE
阅读更多
关键代码:
private static class PieRenderer {
		private static final Paint[] COLORS = { Color.RED, Color.YELLOW,
				Color.GRAY, Color.MAGENTA, Color.ORANGE, Color.GREEN,
				Color.DARK_GRAY, Color.CYAN, Color.PINK, Color.BLUE,
				Color.LIGHT_GRAY };

		public void setColor(PiePlot plot, CategoryDataset dataset) {
			List keys = dataset.getRowKeys();
			for (int i = 0; i < keys.size(); i++) {
				plot.setSectionPaint(keys.get(i).toString(), COLORS[i
						% COLORS.length]);
			}
		}
	}

PieRenderer renderer = new PieRenderer();
		renderer.setColor(localPiePlot, paramCategoryDataset);

参考网站http://balajinatarajan.blogspot.com/2008/04/customizing-jfreechart-pie-chart.html
Introduction

Dynamic representation of data in picture format is inevitable in this programming era. JFreeChart is one of the best open sources in Java World in providing APIs to display dynamic charts viz., Line Chart, Bar Chart, Pie Chart etc., A wide collection of APIs are available under LGPL license not only to generate different charts but also to customize the generated charts with our own look and feel. My projects are basically Portal Applications that involve displaying a Pie Chart for the backend data. As the creation of pie chart just takes two or three lines, I felt it is important to explore more ways to customize the chart generated and the result is this blog. Following section briefly describes various ways to customize pie chart generated using JFreeChart.

Getting Started

For generating and displaying JFreeCharts we need to include certain libraries which are available in JFreeChart web page.
Place these jar files in your WEB-INF/lib folder:


1.jfreechart-*.jar
2.jcommon-*.jar

Creating a Pie Chart using JFreeChart libraries


Creation of pie chart won’t take you too many lines as it mainly needs the dataset for which you need to generate the chart apart from other details like Chart Title, Flag to say whether we need Legend or not etc., Following code shows a way to create a pie chart with available dataset and customize it in many available ways.


1:  import java.awt.Color;
2:  import java.text.AttributedString;
3:  import java.util.List;
4:  import org.jfree.chart.ChartFactory;
5:  import org.jfree.chart.JFreeChart;
6:  import org.jfree.chart.labels.PieSectionLabelGenerator;
7:  import org.jfree.chart.plot.PiePlot;
8:  import org.jfree.chart.plot.Plot;
9:  import org.jfree.chart.title.TextTitle;
10: import org.jfree.data.general.DefaultPieDataset;
11: import org.jfree.data.general.PieDataset;
12: import org.jfree.ui.RectangleInsets;
13: import org.jfree.util.UnitType;

    /*
    * This class is used to create a sample pie chart using JFreeChart and customize it
    */
14: public class CustomizePieChart {
15: public static JFreeChart customizeSamplePieChart( ) {
     /* Creating a sample Pie Dataset */
16:  final DefaultPieDataset data =
     new DefaultPieDataset ( );
  
     /* Storing the sample Pie Chart Data in Pie dataset */
17:  data.setValue("Software Engineer",50);
18:  data.setValue("Programmer Analyst",20);
19:  data.setValue("Technical Specialist",25);
20:  data.setValue("Project Manager",10);

    /* Create a Pie Chart */
    /* Let the Legend be present */
21:  final boolean withLegend = true;
22:  final JFreeChart chart =
    ChartFactory.createPieChart("Employee Survey", 
    data, withLegend, true, true );
  
     /* Creating a pieplot so as to customize the chart  generated */
23:  final PiePlot plot = (PiePlot)chart.getPlot( );

     /* Customizing Label using an inner class */
24:  plot.setLabelGenerator(new CustomLabelGenerator( ));
  
     /* Setting the BackGround Paint for Label */
25:  plot.setLabelBackgroundPaint(Color.WHITE);

Customizing a Pie Chart by creating a PiePlot


In order to customize a pie chart we need to create a plot of type PiePlot. PiePlot extends basic Plot and this plot instance is provided by a static method of JFreeChart. Once a plot is obtained we can do dozens of customizations.

Customizing Pie Chart’s label


If you have a view at dataset for which the chart will be generated, it is just a collection of (name, value) pairs. Pie chart is generated for value parameter (which must be parsable into double) whereas labels and legends are displayed based on the name given. In order to customize label, we need to create an inner class within the class in which the pie chart is generated and pass an instance of that inner class (where we set some rules of how to display the label) to a method in PiePlot which displays the label the way we defined it in the inner class. See Line no. 24 for the PiePlot’s set method and Line no. 39 for static inner class that defines how label should be displayed.


We can also customize other properties of label using PiePlot. This includes,


1.Setting Label Background
2.Setting Label outline
3.Setting Label shadow
4.Disabling label links etc.,

Customizing Pie Chart’s legend


A pie chart’s legend is optional and if we wish to have, we can also customize it the way we did for label. See Line no. 28 for PiePlot’s set method and line no. 46 for static inner class that defines how legend should be displayed. We can also set the Legend items’ shape to pre-defined shapes and the default one is circle.


     /* Setting the Outline paint for the labels */
23:  plot.setLabelOutlinePaint(Color.WHITE);

     /* Setting the Label Shadow Paint */
24:  plot.setLabelShadowPaint(Color.WHITE);

     /* Setting Legend Item Shape (Default is Circle Shape) */
25:  plot.setLegendItemShape(Plot.DEFAULT_LEGEND_ITEM_BOX);

26:  plot.setBaseSectionOutlinePaint(Color.LIGHT_GRAY);
27:  plot.setShadowPaint(Color.WHITE);


     /* Customizing Label using an inner class */
28:  plot.setLegendLabelGenerator(new CustomLegendGenerator());


     /* Creating a Title Object and setting its value */
29:  TextTitle title =
             new TextTitle("Employee Survey");

     /* Setting the Background Paint for the title */
30:  title.setBackgroundPaint(new Color(0.294f, 0.0f, 0.513f));

     /* Setting the font paint for the title */
31:  title.setPaint(new
             Color(1.0f, 0.549f, 0.0f));

     /* Expanding the title to the entire width of the pie chart image */
32:  title.setExpandToFitSpace(true);

     /* Setting the title instance to the chart, atlast */
33:  chart.setTitle(title);


     /* Setting insets to the pie chart image */
34:  plot.setInsets(new 
             RectangleInsets(UnitType.ABSOLUTE, 0.0, 0.0,1.0, 1.0));


     /* Specifying list of colors from which a Pie Section should be painted based on our choice */
35:  Color[] colors = {Color.blue, Color.yellow,
            Color.green, Color.GRAY};

     /* Delegating the choice of color to an inner class */
36:  PieRenderer renderer = new PieRenderer(colors);
37:  renderer.setColor(plot, data);

     /* Returns the chart with customization */
38:  return chart;
}

Customizing Pie Chart’s Title


A pie chart’s title is defined when a new JFreeChart instance is created. We can also customize the same by creating an instance of type TextTitle and setting properties on created instance. See line no. 29 to 33 for details.

Customizing Pie section colors


When you create a default pie chart, all pie sections will be painted in system selected colors which are random. If you wish to define which pie section should be painted on which color, well, you can do that by creating another inner class that defines the exact selection of colors. See line no. 36 for 54 for more details.

Miscellaneous customizations


Apart from aforementioned customizations, following are the miscellaneous ones that I hope will be helpful for you.


Setting insets

Insets for a pie chart can be customized and we can even set ZERO inset.
See line no. 34 for ZERO insets.

Setting paints for BaseSection and Shadow.



39: static class CustomLabelGenerator implements PieSectionLabelGenerator {
    /**
    * Set customized label in the pie chart
    *
    * @param dataset PieChart DataSet
    * @param key Comparable Key
    * @return String Result String to be displayed
    */
40: public String generateSectionLabel(final PieDataset dataset,
        final Comparable key) {
/* Creating a temporary string to hold value defined by us */
41: String temp = null;
42: if (dataset != null) {
/* Assigning the Value from dataset as a label for display */
43: temp = dataset.getValue(key).toString();
/* Modifying a particular label based on the Key name */
44: if(key.toString().equalsIgnoreCase("Software

Engineer")) {
temp = temp + "(Trainees Not Included)";
}
}
/* Returning the formatted string back to set the label */
45: return temp;
}
}


46: static class CustomLegendGenerator
implements PieSectionLabelGenerator {
/**
* Set customized legend in the pie chart
*
* @param dataset PieChart DataSet
* @param key Comparable Key
* @return Result String to be displayed
*/
47: public String

generateSectionLabel(final PieDataset dataset,
final Comparable key) {
/* Creating a temporary string to hold value defined by us */
48: String temp = null;
49: if (dataset != null) {
/* Assigning the Value from dataset as a legend item for display */
50: temp = key.toString();
/* Modifying a particular legend item based on the Key name */
51: if(key.toString().equalsIgnoreCase("Software

Engineer")) {
52:  temp = temp + "(Trainees

Not Included)";
}
}
/* Returning the formatted string back to set the label */
53: return temp;
}
}



54: static class PieRenderer
{
/* Declaring an array of Color variables for storing a list   of  Colors */
55:      private Color[ ]

color;

/* Constructor to initialize PieRenderer class */
56:      public PieRenderer(Color[ ] color)
    {
57:       this.color = color;
    }

/**
* Set Method to set colors for pie sections based on our choice
* @param plot PiePlot of PieChart
* @param dataset PieChart DataSet
*/
58:      public void setColor(PiePlot plot,
DefaultPieDataset dataset)
  {
59:       List keys = dataset.getKeys();
60:            int aInt;

61:            for (int i =

0; i <

keys.size(); i++)
        {
62:                aInt = i % this.color.length;
63:          plot.setSectionPaint(
keys.get(i).toString(),this.color[aInt]);
        }
}
}
}

Generated Output


Following are the sample outputs that will show differences between a generic and customized chart. Since the project I involved is basically a web application I used a servlet to display all these charts.

 

Fig 1: Generic Chart – Not Customized Fig 2: Chart with customized label


 

Fig 3: Chart with customized legend Fig 4: Chart with customized title


 

Fig 5: Chart with ZERO insets Fig 6: Chart with custom pie section colors


Note: Copy the war file into the webapps folder of the Tomcat. Start the Tomcat server & view the charts (JSP) through a browser. [In the address bar give: http://localhost:/CustomizePieChart]
分享到:
评论
1 楼 hellodajun 2012-02-28  

试用一下

相关推荐

    20201012JFreeChart生成饼图和环图技术.zip

    4. **自定义图表属性**:JFreeChart允许我们对图表进行高度定制,包括设置标题、颜色、标签样式等。这可以通过`ChartCustomizer`或直接修改`Chart`对象的属性来实现。 5. **绘制图表**:最后,使用`ChartUtilities`...

    JFreeChart绘制饼图,折线图,柱状图demo

    在实际应用中,开发者可以根据需求调整数据集、自定义图表颜色、字体、标题、图例等属性,以满足各种视觉和功能性需求。`testJFreechart`这个压缩包文件很可能包含了上述三种类型的图表示例代码,你可以通过解压并...

    jfreechart做饼图需要的jcommon-1.0.0-rc1.jar和jfreechart-1.0.0-rc1.jar两个jar包.rar

    开发者可以利用这个库来创建自定义的饼图,通过调整各种参数来实现所需的效果,如饼片的颜色、大小、标签、阴影等。 要使用这两个JAR包,你需要将它们添加到项目的类路径中。在传统的Java项目中,这可以通过在IDE的...

    JFreeChart 饼图、柱状图 例 (含数据库)

    JFreeChart允许你创建垂直或水平的柱状图,并可以自定义轴标签、颜色和数据标签。结合数据库,柱状图可以用来展示一段时间内的销售数据或者不同地区的用户分布等。 在MyEclipse环境中,你可能需要先导入JFreeChart...

    JFreechart自定义图例

    **JFreeChart自定义图例** 在Java编程中,JFreeChart是一个强大的库,用于创建各种图表,如折线图、柱状图、饼图等。这个库在数据可视化方面非常有用,尤其对于数据分析和报告生成。在某些情况下,我们可能需要对...

    java绘制图表(柱状图、饼图、折线图)包 jfreechart

    JFreeChart提供了多种自定义选项,如柱体颜色、标签、图例等。你可以创建一个`CategoryDataset`对象,将数据组织成类别和值,然后使用`JFreeChart`的`createBarChart()`方法来生成柱状图。 饼图是另一种常用的数据...

    JFreeChart饼图、柱状图等

    每个数据点的位置由其对应的两个变量决定,JFreeChart允许我们自定义点的形状、大小和颜色。 在使用JFreeChart时,通常需要先创建一个CategoryDataset或XYDataset,然后用这个数据集来构建图表。JFreeChart提供了...

    JfreeChart柱状图饼图

    3. **自定义样式**:JFreeChart提供了丰富的自定义选项,包括颜色、标签、图例、背景等。例如,可以设置`CategoryPlot`的背景色,调整`CategoryAxis`和`ValueAxis`的显示样式。 4. **渲染器**:`...

    JFreeChart饼图、折线图等资料学习

    你可以自定义颜色、标签、工具提示和详细信息窗口,使得饼图更具可读性和吸引力。 折线图在统计分析和数据可视化中非常常见。在JFreeChart中,你可以使用`XYDataset`接口存储x-y坐标对数据,然后通过`XYPlot`类来...

    java jfreechart 生成图形报表 饼图,条形图,曲线图

    JFreeChart 支持多种图表类型,包括饼图、条形图和曲线图,这些图表在数据可视化中有着广泛的应用。在Java开发中,JFreeChart 提供了一个简单而灵活的API,使得开发者可以轻松地创建出丰富的图表展示数据。 首先,...

    jfreechart曲线图饼图柱状图 免费图标 图表

    JFreeChart支持多种图表类型,如折线图(曲线图)、饼图、柱状图、散点图、甘特图等,同时提供了自定义样式和颜色配置的灵活性。 ### 2. 曲线图 曲线图(Line Chart)是表示数据趋势的理想选择。使用JFreeChart...

    jfreechart 图形折线,饼图,柱状图等

    除了基本的图表类型,JFreeChart 还支持自定义颜色、标签、图例、背景、网格线等样式。此外,还可以添加工具提示和URL链接到图表元素,实现交互式效果。对于 Web 应用,JFreeChart 可以与 Servlets 结合,生成动态...

    jfreechart 生成折线图,饼图,柱状图,堆栈柱状图

    3. **自定义设置**:使用`ChartCustomizer`或者直接调用图表对象的方法来调整细节,如调整轴范围、添加图例、改变系列颜色等。 4. **渲染和输出**:最后,可以将图表渲染为图像(如PNG或JPEG),也可以嵌入到Swing...

    自定义JFreeChart柱状图的详细说明

    在Java编程领域,JFreeChart是一个非常流行的图表库,它提供了丰富的图表类型,包括柱状图、饼图、线图等,便于开发者创建出专业且美观的数据可视化展示。本篇文章将详细探讨如何自定义JFreeChart的柱状图,使其适应...

    jfreechart 曲线图 3d饼图 3d柱状图

    饼图的每个部分可以通过颜色、标签和工具提示进行自定义。 4. **3D柱状图(bar.jpg)** 创建3D柱状图,可以使用`ChartFactory.createBarChart3D()`方法。同样,你需要一个`CategoryDataset`,其中包含行标识(类别...

    饼形图、柱形图实例 jfreechart (Java)

    3. 自定义图表:可以通过`CategoryPlot`类调整柱形图的外观,如条形宽度、颜色等。 4. 显示或保存:与饼图一样,可以在Swing组件中显示或保存为图像。 在处理中文乱码问题时,主要涉及到JFreeChart的文本渲染。由于...

    JFreeChart图形控件

    开发者可以根据需求自定义颜色、标签、图例、网格线等元素,甚至可以创建动态图表,通过动画展示数据变化。此外,JFreeChart支持导出图表为多种格式,如JPEG、PNG、PDF等,方便在报告、网页和应用程序中使用。 总之...

Global site tag (gtag.js) - Google Analytics