jFreeChart柱形图

合集下载

关于JfreeChart柱状图,数值显示的问题

关于JfreeChart柱状图,数值显示的问题

关于JfreeChart柱状图,数值显示的问题关于JfreeChart柱状图,数值显示的问题你试试这句话:BarRenderer renderer=new BarRenderer();renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());renderer.setBaseItemLabelsVisible(true);关于JFreeChart生成柱状图的问题,急!一个简单的方法根据PlotRenderingInfo 获得getDataArea() getPlotArea()PlotArea 包括座标轴 getDataArea 只有影象两个区域相减,左边的就是纵轴的区域。

关于Excel柱状图的问题++++57132899++++图表是通过资料位置生成的jfreechart 柱状图横轴下方的图示的排列问题:jfree./jfreechart/samples.这个是Demo。

点选web start 启动例子,里面有很多很多的例子有一个例子叫LegendWrapperDemo1.java 的那个demo 就是竖着排的。

柱中用不同颜色的也有。

我的专案中用的就是不同颜色的,在demo里的Bar Charts -Stacked的目录下都是那种例子。

我就是照那个做的。

原始码在;:sourcefe./projects/jfreechart/files/这个页面上下载。

jfreechart是开源的。

技术支援的文件是收费的怎么在jqplot 柱状图每条柱上显示数值axes: { xaxis: { label: "X 轴文字" } 看看例子就能发现啊$(document).ready(function(){ var plot2 = $.jqplot ('chart2', [[3,7,9,1,4,6,8,2,5]], { Give the plot a title. title: 'Plot With Options', You can specify options for...点“柱状图里的柱子”——右键——资料系列格式——资料标志——值(勾选)——确定java中使用jfreechart做柱状图,在jsp中显示有问题,jfreechart中显示柱状图到jsp页面:package .test.jfreechart;import java.awt.Font;import javax.swing.JPanel;import .jfree.chart.ChartFactory;import .jfree.chart.ChartPanel;import .jfree.chart.JFreeChart;import .jfree.chart.axis.CategoryAxis;import .jfree.chart.plot.CategoryPlot;import .jfree.chart.plot.PlotOrientation;import .jfree.chart.title.TextTitle;import .jfree.data.category.CategoryDataset;import .jfree.data.category.DefaultCategoryDataset;import .jfree.ui.ApplicationFrame;public class JFreeChartTest2 extends ApplicationFrame{public JFreeChartT est2(String title){super(title);this.setContentPane(createPanel()); 建构函式中自动建立Java 的panel面板}public static CategoryDataset createDataset() 建立柱状图资料集{DefaultCategoryDataset dataset=new DefaultCategoryDataset();dataset.setValue(10,"a","管理人员");dataset.setValue(20,"b","市场人员");dataset.setValue(40,"c","开发人员");dataset.setValue(15,"d","其他人员");return dataset;}public static JFreeChart createChart(CategoryDataset dataset) 用资料集建立一个图表{JFreeChart chart=ChartFactory.createBarChart("hi", "人员分布","人员数量", dataset, PlotOrientation.VERTICAL, true, true, false); 建立一个JFreeChartchart.setTitle(new TextTitle("某公司组织结构图",new Font("宋体",Font.BOLD+Font.ITALIC,20)));可以重新设定标题,替换“hi”标题CategoryPlot plot=(CategoryPlot)chart.getPlot();获得图示中间部分,即plotCategoryAxis categoryAxis=plot.getDomainAxis();获得横座标categoryAxis.setLabelFont(new Font("微软雅黑",Font.BOLD,12));设定横座标字型return chart;}public static JPanel createPanel(){JFreeChart chart =createChart(createDataset());return new ChartPanel(chart); 将chart物件放入Panel面板中去,ChartPanel类已继承Jpanel}public static void main(String[] args){JFreeChartTest2 chart=new JFreeChartTest2("某公司组织结构图");chart.pack();以合适的大小显示chart.setVisible(true);}}执行结果:java jfreechart 柱状图设定问题,求解参考答案总有一天,我会丢下我所有的疲倦和理想,带着我的相机,远离繁华,面向空旷。

免费 jfreechart_生成折线图,饼图,柱状图,堆栈柱状图

免费 jfreechart_生成折线图,饼图,柱状图,堆栈柱状图

最近公司使用jfreechart来生成统计图,使用了折线图,饼图等,因为用的1.0.8a版的jfreechart,与1.0.0版本的地方有很多不同,而且图片生成清晰度比老版的高,如下是我做的demo.1.所需包(1) jfreechart-1.0.8a.jar(2) jcommon-1.0.12.jar2.运行环境JDK 1.53.源代码import java.awt.Color;import java.awt.Font;import java.io.File;import java.io.FileOutputStream;import java.text.DecimalFormat;import java.text.NumberFormat;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.CategoryAxis;import org.jfree.chart.axis.CategoryLabelPositions;import org.jfree.chart.axis.NumberAxis;import org.jfree.chart.axis.V alueAxis;import bels.StandardCategoryItemLabelGenerator;import bels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PiePlot3D;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.renderer.category.BarRenderer;import org.jfree.chart.renderer.category.LineAndShapeRenderer;import org.jfree.chart.renderer.category.StackedBarRenderer;import org.jfree.chart.title.TextTitle;import org.jfree.data.category.CategoryDataset;import org.jfree.data.general.DatasetUtilities;import org.jfree.data.general.DefaultPieDataset;import org.jfree.data.general.PieDataset;/*** 实际取色的时候一定要16位的,这样比较准确** @author new*/public class CreateChartServiceImpl{private static final String CHART_PA TH = "E:/test/";public static void main(String[] args){// TODO Auto-generated method stubCreateChartServiceImpl pm = new CreateChartServiceImpl();// 生成饼状图pm.makePieChart();// 生成单组柱状图pm.makeBarChart();// 生成多组柱状图pm.makeBarGroupChart();// 生成堆积柱状图pm.makeStackedBarChart();// 生成折线图pm.makeLineAndShapeChart();}/*** 生成折线图*/public void makeLineAndShapeChart(){double[][] data = new double[][]{{ 672, 766, 223, 540, 126 },{ 325, 521, 210, 340, 106 },{ 332, 256, 523, 240, 526 } };String[] rowKeys ={ "苹果", "梨子", "葡萄" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createTimeXYChar("折线图", "x轴", "y轴", dataset, "lineAndShap.png"); }/*** 生成分组的柱状图*/public void makeBarGroupChart(){double[][] data = new double[][]{ 672, 766, 223, 540, 126 },{ 325, 521, 210, 340, 106 },{ 332, 256, 523, 240, 526 } };String[] rowKeys ={ "苹果", "梨子", "葡萄" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createBarChart(dataset, "x坐标", "y坐标", "柱状图", "barGroup.png");}/*** 生成柱状图*/public void makeBarChart(){double[][] data = new double[][]{{ 672, 766, 223, 540, 126 } };String[] rowKeys ={ "苹果" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createBarChart(dataset, "x坐标", "y坐标", "柱状图", "bar.png");}/*** 生成堆栈柱状图*/public void makeStackedBarChart(){double[][] data = new double[][]{{ 0.21, 0.66, 0.23, 0.40, 0.26 },{ 0.25, 0.21, 0.10, 0.40, 0.16 } };String[] rowKeys ={ "苹果", "梨子" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createStackedBarChart(dataset, "x坐标", "y坐标", "柱状图", "stsckedBar.png"); }/*** 生成饼状图*/public void makePieChart(){double[] data ={ 9, 91 };String[] keys ={ "失败率", "成功率" };createValidityComparePimChar(getDataPieSetByUtil(data, keys), "饼状图", "pie2.png", keys);}// 柱状图,折线图数据集public CategoryDataset getBarData(double[][] data, String[] rowKeys, String[] columnKeys){return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);}// 饼状图数据集public PieDataset getDataPieSetByUtil(double[] data,String[] datadescription){if (data != null && datadescription != null){if (data.length == datadescription.length){DefaultPieDataset dataset = new DefaultPieDataset();for (int i = 0; i < data.length; i++){dataset.setValue(datadescription[i], data[i]);}return dataset;}}return null;/*** 柱状图**@param dataset 数据集* @param xName x轴的说明(如种类,时间等)* @param yName y轴的说明(如速度,时间等)* @param chartTitle 图标题* @param charName 生成图片的名字* @return*/public String createBarChart(CategoryDataset dataset, String xName,String yName, String chartTitle, String charName){JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);/** V ALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭,* 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看*///chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.V ALUE_TEXT_ANTIALIAS_OFF);chart.setTextAntiAlias(false);chart.setBackgroundPaint(Color.white);// create plotCategoryPlot plot = chart.getCategoryPlot();// 设置横虚线可见plot.setRangeGridlinesVisible(true);// 虚线色彩plot.setRangeGridlinePaint(Color.gray);// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();// vn.setAutoRangeIncludesZero(true);DecimalFormat df = new DecimalFormat("#0.00");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式// x轴设置CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值// Lable(Math.PI/3.0)度倾斜// domainAxis.setCategoryLabelPositions(CategoryLabelPositions// .createUpRotationLabelPositions(Math.PI / 3.0));domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的Lable 是否完整显示// 设置距离图片左端距离domainAxis.setLowerMargin(0.1);// 设置距离图片右端距离domainAxis.setUpperMargin(0.1);// 设置columnKey 是否间隔显示// domainAxis.setSkipCategoryLabelsToFit(true);plot.setDomainAxis(domainAxis);// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)plot.setBackgroundPaint(new Color(255, 255, 204));// y轴设置ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(labelFont);rangeAxis.setTickLabelFont(labelFont);// 设置最高的一个Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);BarRenderer renderer = new BarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.05);// 设置柱子高度renderer.setMinimumBarLength(0.2);// 设置柱子边框颜色renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱子边框可见renderer.setDrawBarOutline(true);// // 设置柱的颜色renderer.setSeriesPaint(0, new Color(204, 255, 255));renderer.setSeriesPaint(1, new Color(153, 204, 255));renderer.setSeriesPaint(2, new Color(51, 204, 204));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.0);// 显示每个柱的数值,并修改该数值的字体属性renderer.setIncludeBaseInRange(true);renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(1.0f);FileOutputStream fos_jpg = null;try{isChartPathExist(CHART_PATH);String chartName = CHART_PA TH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);return chartName;}catch (Exception e){e.printStackTrace();return null;}finally{try{fos_jpg.close();}catch (Exception e){e.printStackTrace();}}/*** 横向图** @param dataset 数据集* @param xName x轴的说明(如种类,时间等)* @param yName y轴的说明(如速度,时间等)* @param chartTitle 图标题* @param charName 生成图片的名字* @return*/public String createHorizontalBarChart(CategoryDataset dataset,String xName, String yName, String chartTitle, String charName){JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);CategoryPlot plot = chart.getCategoryPlot();// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();//设置刻度必须从0开始// vn.setAutoRangeIncludesZero(true);DecimalFormat df = new DecimalFormat("#0.00");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的// LableFont labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值domainAxis.setMaximumCategoryLabelWidthRatio(0.8f);// 横轴上的Lable 是否完整显示// domainAxis.setVerticalCategoryLabels(false);plot.setDomainAxis(domainAxis);ValueAxis rangeAxis = plot.getRangeAxis();// 设置最高的一个Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);BarRenderer renderer = new BarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.03);// 设置柱子高度renderer.setMinimumBarLength(30);renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱的颜色renderer.setSeriesPaint(0, Color.GREEN);renderer.setSeriesPaint(1, new Color(0, 0, 255));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.5);// 显示每个柱的数值,并修改该数值的字体属性renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); // 设置柱的数值可见renderer.setBaseItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(0.6f);FileOutputStream fos_jpg = null;try{isChartPathExist(CHART_PATH);String chartName = CHART_PA TH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);return chartName;}catch (Exception e){e.printStackTrace();return null;}finally{try{fos_jpg.close();}catch (Exception e){e.printStackTrace();}}}/*** 饼状图** @param dataset 数据集* @param chartTitle 图标题* @param charName 生成图的名字* @param pieKeys 分饼的名字集* @return*/public String createValidityComparePimChar(PieDataset dataset,String chartTitle, String charName, String[] pieKeys){JFreeChart chart = ChartFactory.createPieChart3D(chartTitle, // chart// titledataset,// datatrue,// include legendtrue, false);// 使下说明标签字体清晰,去锯齿类似于//chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.V ALUE_TEXT_ANTIALIAS_OFF);的效果chart.setTextAntiAlias(false);// 图片背景色chart.setBackgroundPaint(Color.white);// 设置图标题的字体重新设置titleFont font = new Font("隶书", Font.BOLD, 25);TextTitle title = new TextTitle(chartTitle);title.setFont(font);chart.setTitle(title);PiePlot3D plot = (PiePlot3D) chart.getPlot();// 图片中显示百分比:默认方式// 指定饼图轮廓线的颜色// plot.setBaseSectionOutlinePaint(Color.BLACK);// plot.setBaseSectionPaint(Color.BLACK);// 设置无数据时的信息plot.setNoDataMessage("无对应的数据,请重新查询。

JFreechart绘图_柱状图

JFreechart绘图_柱状图

1、数据结构2、最终结果3、操作类public class BarTest {private static final long serialVersionUID=11;/*** 生成制图对象*@param is3D 是否为3D效果*@return JFreeChart对象*/public static JFreeChart createChart() {JFreeChart chart =null;chart = ChartFactory. createBarChart3D("柱状图","种类","数字",createDaSet(),PlotOrientation.VERTICAL,true,true,false);//设置柱状图,主标题的文字chart.setTitle(new TextTitle("柱状图",new Font("宋体",Font.BOLD+Font.ITALIC,20)));//设置柱状图最下方说明文字chart.getLegend().setItemFont(new Font("微软雅黑",Font.BOLD,12));CategoryPlot plot=chart.getCategoryPlot();plot.setForegroundAlpha(0.5F);//设置透明度,0.5F,1为不透明,0为全透明CategoryAxis axis=plot.getDomainAxis();//设置X轴坐标上标题的文字axis.setLabelFont(new Font("微软雅黑",Font.BOLD,18));//设置X轴坐标上的文字axis.setTickLabelFont(new Font("微软雅黑",Font.BOLD,12));ValueAxis valueAxis=plot.getRangeAxis();//设置Y轴坐标上标题的文字valueAxis.setLabelFont(new Font("微软雅黑",Font.BOLD,18));//设置Y轴坐标上的文字valueAxis.setTickLabelFont(new Font("微软雅黑",Font.BOLD,12));//设置网格背景颜色plot.setBackgroundPaint(Color.white);//设置网格竖线颜色plot.setDomainGridlinePaint(Color.pink);//设置网格横线颜色plot.setRangeGridlinePaint(Color.pink);//显示每个柱的数值,并修改该数值的字体属性BarRenderer3D render=new BarRenderer3D();render.setBaseItemLabelGenerator(new StandardCateg oryItemLabelGenerator());render.setBaseItemLabelsVisible(true);render.setBaseItemLabelPaint(Color.black);render.setBaseItemLabelFont(new Font("黑体",Font.BOLD,12));//默认的数字显示在柱子中,调整数字的显示render.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT));render.setItemLabelAnchorOffset(10D);//设置每个地区所包含的平行柱之间的距离//render.setItemMargin(0.3);plot.setRenderer(render);//设置横轴、纵轴的显示位置plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_ RIGHT);plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_L EFT);return chart;}/*** 创建CategoryDataset对象,连接数据库,获取数据*@return*/public static CategoryDataset createDaSet(){// 获取数据库连接Connection conn = ConnectionManager. getConnection();JDBCCategoryDataset dataset =null; //数据集合try{// 通过JDBC创建数据集合dataset =new JDBCCategoryDataset(conn);// SQL语句String sql ="select a.rolename,count(*) 功能数 from yxz_user_role a, yxz_role_function b, "+" yxz_system_function c whereb.functionid =c.fun_id and a.roleid = b.roleid group by a.rolename ";//System.out.println(sql);// 查询并向数据集合中添加数据dataset.executeQuery(sql);}catch(Exception e) {e.printStackTrace();}finally{// 关闭数据库连接ConnectionManager. closeConnection(conn);}return dataset;}//生成图片public static String saveAsFile(JFreeChart chart,String outputPath,int width,int height){FileOutputStream out=null;try{File file=new File(outputPath);if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}out=new FileOutputStream(outputPath);//保存图片ChartUtilities. writeChartAsPNG(out, chart, width, height);//ChartUtilities.writeChartAsJPEG(out, chart, width, height);out.flush();}catch(FileNotFoundException e) {e.printStackTrace();}catch(Exception e) {e.printStackTrace();}finally{if(out !=null) {try{out.close();}catch(IOException e) {}}}return outputPath;}public static void main(String[] args) {//步骤2:根据Dataset 生成JFreeChart对象,以及做相应的设置JFreeChart chart = BarTest. createChart();BarTest. saveAsFile(chart,"c:\\jfreechart\\bar1.png", 500, 400);}}。

jFreeChart图形显示设置(柱状图)

jFreeChart图形显示设置(柱状图)

jFreeChart图形显示设置(柱状图)说明表源代码://BarRenderer3Dprivate JFreeChart createChartPole(CategoryDataset dcd) { // 构造基本的JFreeChartsetTitle(Title);setXAxisTitle(x);setYAxisTitle(y);JFreeChart chart = ChartFactory.createBarChart3D(getTitle(), getXAxisTitle(), getYAxisTitle(), dcd,PlotOrientation.VERTICAL, true, true, false);CategoryPlot plot = (CategoryPlot)chart.getPlot();BarRenderer3D custombarrenderer3d = new BarRenderer3D();//设置图例LegendTitle legtitle = chart.getLegend();//设置图例字体legtitle.setItemFont(new Font("黑体", Font.ROMAN_BASELINE, 15));//取得chart图的标题TextTitle title = chart.getTitle();//设置chart图标题的字体title.setFont(new Font("黑体", Font.CENTER_BASELINE, 24));//X轴字体CategoryAxis domainAxisTemp = plot.getDomainAxis();domainAxisTemp.setLabelFont(new Font("黑体", Font.ROMAN_BASELINE, 12));//设置x轴各项标题的字体domainAxisTemp.setTickLabelFont(new Font("黑体",Font.ROMAN_BASELINE, 12));domainAxisTemp.setTickLabelPaint(Color.BLUE);//Y轴字体ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(new Font("黑体", Font.ROMAN_BASELINE, 12));//custombarrenderer3d.setBaseOutlinePaint(Color.blue);custombarrenderer3d.setWallPaint(Color.lightGray);// 3D坐标轴的墙体颜色custombarrenderer3d.setMinimumBarLength(0.01);custombarrenderer3d.setMaximumBarWidth(0.05);//控制X轴坐标点文字角度当X轴的坐标点超过15个时,文字角度调整为45度向上if(dcd.getColumnCount() > 8){chart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions (CategoryLabelPositions.DOWN_45);// 设置坐标点标记与坐标轴之间的距离//jfreechart.getCategoryPlot().getDomainAxis().setCategoryLabelPosi tionOffset(50);//jf.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(Ca tegoryLabelPositions.createUpRotationLabelPositions(Math.PI/6));}// 显示每个柱的数值,并修改该数值的字体属性<BR>custombarrenderer3d.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());// custombarrenderer3d.setBaseItemLabelFont(new Font("黑体", Font.ROMAN_BASELINE, 12));custombarrenderer3d.setBaseItemLabelFont(new Font("黑体", Font.CENTER_BASELINE, 15));//是否显示柱的数值标签custombarrenderer3d.setBaseItemLabelsVisible(true);// 每个柱的数值,标签显示的方式及位置custombarrenderer3d.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_CENTER));// 标签显示与设定位置的距离custombarrenderer3d.setItemLabelAnchorOffset(10D);// 设置每个基站所包含的平行柱的之间距离custombarrenderer3d.setItemMargin(0.05D);// 设置柱的颜色custombarrenderer3d.setSeriesPaint(0,Color.getHSBColor(3.5f, 2.3f, 4.5f));// 设置柱的 Outline 颜色custombarrenderer3d.setSeriesOutlinePaint(0, Color.BLACK);//为单个柱体设置字体,"1"为柱体的序号// custombarrenderer3d.setSeriesItemLabelFont(1, new Font("宋体", Font.CENTER_BASELINE, 72));// 各柱体的宽度custombarrenderer3d.setMaximumBarWidth(0.050000000000000003D);plot.setRenderer(custombarrenderer3d);return chart;}。

关于JFreeChart的饼形图、柱形图实例及中文乱码解决方案

关于JFreeChart的饼形图、柱形图实例及中文乱码解决方案

示例1为纯Java饼形图实例示例2为jsp页面饼形图实例示例3为jsp页面柱形图实例示例1import java.awt.Color;import java.awt.Font;import java.awt.RenderingHints;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartFrame;import org.jfree.chart.JFreeChart;import bels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot;import org.jfree.chart.title.T extTitle;import org.jfree.data.general.DefaultPieDataset;public class TestPieChart {public static void createPieChart() {//用工厂类创建饼图JFreeChart pieChart = ChartFactory.createPieChart("",createDataset(), true, true, false);//用于解决标题中文乱码TextTitle title=new TextTitle("数据4-8",new Font("宋体", Font.PLAIN, 12));pieChart.setTitle(title);//用于解决底部中文乱码pieChart.getLegend().setItemFont(new Font("宋体",Font.PLAIN,12));// RenderingHints做文字渲染参数的修改// VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭.pieChart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);//得到饼图的Plot对象PiePlot piePlot = (PiePlot) pieChart.getPlot();setSection(piePlot);setLabel(piePlot);setNoDataMessage(piePlot);setNullAndZeroValue(piePlot);//将饼图显示在图像界面上ChartFrame frame = new ChartFrame("TestPieChart", pieChart);frame.pack();frame.setVisible(true);}public static DefaultPieDataset createDataset() {//设置数据DefaultPieDataset pieDataset = new DefaultPieDataset();pieDataset.setValue("经济", 0.1);pieDataset.setValue("政治", 3.63);pieDataset.setValue("车次", 2.84);pieDataset.setValue("里程", 2.1);pieDataset.setValue("秋", 2.80);return pieDataset;}public static void setSection(PiePlot pieplot) {//设置扇区颜色pieplot.setSectionPaint("经济", new Color(255, 142, 255));pieplot.setSectionPaint("政治", new Color(210, 128, 223));pieplot.setSectionPaint("车次", new Color(100, 96, 191));pieplot.setSectionPaint("里程", new Color(64, 255, 128));//设置扇区分离显示pieplot.setExplodePercent("秋", 0.2D);//设置扇区边框不可见pieplot.setSectionOutlinesVisible(false);}public static void setLabel(PiePlot pieplot) {//设置扇区标签显示格式:关键字:值(百分比)pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator( "{0}:{1}({2} percent)"));//设置扇区标签颜色pieplot.setLabelBackgroundPaint(new Color(220, 220, 220));pieplot.setLabelFont((new Font("宋体", Font.PLAIN, 12)));}public static void setNoDataMessage(PiePlot pieplot) {//设置没有数据时显示的信息pieplot.setNoDataMessage("无数据");//设置没有数据时显示的信息的字体pieplot.setNoDataMessageFont(new Font("宋体", Font.BOLD, 14));//设置没有数据时显示的信息的颜色pieplot.setNoDataMessagePaint(Color.red);}public static void setNullAndZeroValue(PiePlot piePlot) {//设置是否忽略0和null值piePlot.setIgnoreNullValues(true);piePlot.setIgnoreZeroValues(true);}public static void main(String[] args) {createPieChart();}}示例2<%@ page language="java" import="java.io.*" pageEncoding="utf-8"%> <%@ page import="org.jfree.data.general.DefaultPieDataset"%><%@ page import="org.jfree.chart.*"%><%@ page import="org.jfree.chart.plot.*"%><%@ page import="org.jfree.chart.servlet.ServletUtilities"%><%@ page import="bels.StandardPieToolTipGenerator"%> <%@ page import="org.jfree.chart.urls.StandardPieURLGenerator"%><%@ page import="org.jfree.chart.entity.StandardEntityCollection"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>图形</title></head><body><%DefaultPieDataset data = new DefaultPieDataset();//数据初始化data.setValue("高中以下",380);data.setValue("高中",1620);data.setValue("大专",6100);data.setValue("本科",8310);data.setValue("硕士",3520);data.setValue("博士",180);//HttpSession session = request.getSession();PiePlot3D plot = new PiePlot3D(data);//生成一个3D饼图//plot.setURLGenerator(newStandardPieURLGenerator("DegreedView.jsp"));//设定图片链接JFreeChart chart = newJFreeChart("",JFreeChart.DEFAULT_TITLE_FONT, plot, true);chart.setBackgroundPaint(java.awt.Color.white);//可选,设置图片背景色chart.setTitle("程序员学历情况调查表-By Alpha");//可选,设置图片标题plot.setToolTipGenerator(newStandardPieToolTipGenerator());StandardEntityCollection sec = newStandardEntityCollection();ChartRenderingInfo info = new ChartRenderingInfo(sec);PrintWriter w = new PrintWriter(out);//输出MAP信息//500是图片长度,300是图片高度//String filename =ServletUtilities.saveChartAsPNG(chart,500,300,info,session);//.pngString filename =ServletUtilities.saveChartAsJPEG(chart,500,300,info,session);//.jpegChartUtilities.writeImageMap(w,"map0",info,true);String graphURL = request.getContextPath() +"/servlet/DisplayChart?filename=" + filename;%><P ALIGN="CENTER"><img src="<%=graphURL %>" width=500 height=300 border=0 usemap="#map0"> </P></body></html>注:web.xml配置<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4"xmlns="/xml/ns/j2ee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/j2ee/xml/ns/j2ee/web-app_2_4.xsd"><servlet><servlet-name>DisplayChart</servlet-name><servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class> </servlet><servlet-mapping><servlet-name>DisplayChart</servlet-name><url-pattern>/servlet/DisplayChart</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>示例3<%@ page language="java" pageEncoding="utf-8"%><%@ page import="org.jfree.chart.ChartFactory"%><%@ page import="org.jfree.chart.ChartUtilities"%><%@ page import="org.jfree.chart.JFreeChart"%><%@ page import="org.jfree.chart.plot.PlotOrientation"%><%@ page import="org.jfree.data.category.DefaultCategoryDataset"%> <%@ page import="java.awt.Color"%><%@ page import="org.jfree.chart.renderer.category.BarRenderer3D"%> <%@ pageimport="bels.StandardCategoryItemLabelGenerator"%> <%@ page import="org.jfree.chart.axis.CategoryAxis"%><%@ page import="org.jfree.chart.plot.CategoryPlot"%><%@ page import="java.awt.*"%><%@ page import="org.jfree.chart.title.TextTitle"%><%@ page import="org.jfree.chart.axis.NumberAxis"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>柱形</title></head><body><%DefaultCategoryDataset dataset = newDefaultCategoryDataset();dataset.addValue(150, " 北京 ", " 苹果 ");dataset.addValue(530, " 上海 ", " 苹果 ");dataset.addValue(160, " 广州 ", " 苹果 ");dataset.addValue(120, " 北京 ", " 梨子 ");dataset.addValue(230, " 上海 ", " 梨子 ");dataset.addValue(360, " 广州 ", " 梨子 ");dataset.addValue(600, " 北京 ", " 葡萄 ");dataset.addValue(430, " 上海 ", " 葡萄 ");dataset.addValue(560, " 广州 ", " 葡萄 ");dataset.addValue(400, " 北京 ", " 香蕉 ");dataset.addValue(530, " 上海 ", " 香蕉 ");dataset.addValue(660, " 广州 ", " 香蕉 ");dataset.addValue(500, " 北京 ", " 荔枝 ");dataset.addValue(630, " 上海 ", " 荔枝 ");dataset.addValue(430, " 广州 ", " 荔枝 ");JFreeChart chart = ChartFactory.createBarChart3D(""," 水果种类-/Alpha/ ", " 销量 ", dataset,PlotOrientation.VERTICAL, true, false, false);chart.setBackgroundPaint(Color.WHITE);CategoryPlot plot = chart.getCategoryPlot();//设置字体,不然会中文乱码的Font font = new Font("宋体", Font.BOLD, 16);TextTitle title = new TextTitle("水果销量图统计-By Alpha", font);chart.setTitle(title); //标题//副标题//TextTitle subtitle = new TextTitle("副标题", new Font("黑体", Font.BOLD,12));//chart.addSubtitle(subtitle);NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();CategoryAxis domainAxis = plot.getDomainAxis();//设置X轴坐标上的文字domainAxis.setTickLabelFont(new Font("sans-serif",Font.PLAIN, 11));//设置X轴的标题文字domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));//设置Y轴坐标上的文字numberaxis.setTickLabelFont(new Font("sans-serif",Font.PLAIN, 12));//设置Y轴的标题文字numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));//底部汉字乱码的问题chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));plot.setDomainAxis(domainAxis);BarRenderer3D renderer = new BarRenderer3D();renderer.setBaseOutlinePaint(Color.BLACK);// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.1);// 显示每个柱的数值,并修改该数值的字体属性renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());renderer.setItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(0.8f);ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart,640, 400);%></body></html>注:示例3中红色字体为解决中文乱码问题,具体见注释。

JfreeChart-连接-数据库-数据显示柱状图

JfreeChart-连接-数据库-数据显示柱状图

首先编写web.xml:<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><servlet><servlet-name>DisplayChart</servlet-name><servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class></servlet><servlet-mapping><servlet-name>DisplayChart</servlet-name><url-pattern>/DisplayChart</url-pattern></servlet-mapping></web-app>显示柱状图代码页:index.jsp:<%@ page contentType="text/html;charset=UTF-8"import="java.sql.*,xuyan.model.*"%><%@ pageimport="org.jfree.chart.ChartFactory,org.jfree.chart.JFreeCha rt,org.jfree.chart.plot.PlotOrientation,org.jfree.chart.servlet.ServletUtilities,org.jfree.data.category.CategoryDataset,org.jfree.data.ge neral.DatasetUtilities,org.jfree.chart.plot.*,bels. *,org.jfree.chart.renderer.category.BarRenderer3D,java.awt.*,org.jfre e.ui.*,org.jfree.chart.axis.AxisLocation,org.jfree.chart.title.TextTi tle,org.jfree.chart.axis.CategoryAxis,org.jfree.chart.axis.NumberAxis "%><%@ pageimport="org.jfree.chart.ChartFactory,org.jfree.chart.JFreeCha rt,org.jfree.chart.plot.PlotOrientation,org.jfree.chart.servlet.Servl etUtilities,org.jfree.data.category.DefaultCategoryDataset"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords"content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><%DefaultCategoryDataset dataset = new DefaultCategoryDataset();Connection con = null;Statement st = null;ResultSet rs = null;//连接数据库con = new ConnDB().GetConn();st = con.createStatement();rs = st.executeQuery("select * from AnimalNum ");while (rs.next()) {dataset.addValue(rs.getInt(3), "北京", rs.getString(2));dataset.addValue(rs.getInt(5), "上海", rs.getString(4));dataset.addValue(rs.getInt(7), "天津", rs.getString(6));}JFreeChart chart = ChartFactory.createBarChart("统计图", "肉类", "销量",dataset, PlotOrientation.VERTICAL, true, true, false);//设置字体,不然会中文乱码的Font font = new Font("宋体", Font.BOLD, 16);TextTitle title = new TextTitle("肉类销量统计图", font);chart.setTitle(title);//标题CategoryPlot plot = chart.getCategoryPlot();NumberAxis numberaxis = (NumberAxis)plot.getRangeAxis();CategoryAxis domainAxis = plot.getDomainAxis();/*------设置X轴坐标上的文字-----------*/domainAxis.setTickLabelFont(newFont("sans-serif", Font.PLAIN, 11));/*------设置X轴的标题文字------------*/domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));/*------设置Y轴坐标上的文字-----------*/numberaxis.setTickLabelFont(newFont("sans-serif", Font.PLAIN, 12));/*------设置Y轴的标题文字------------*/numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));/*------这句代码解决了底部汉字乱码的问题-----------*/chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); //由底部文字才加,不然会出错// 以上为文字设置//以下为背景设置//设置网格背景颜色plot.setBackgroundPaint(Color.white);//设置网格竖线颜色plot.setDomainGridlinePaint(Color.pink);//设置网格横线颜色plot.setRangeGridlinePaint(Color.pink);//显示每个柱的数值,并修改该数值的字体属性BarRenderer3D renderer = new BarRenderer3D();renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());renderer.setBaseItemLabelsVisible(true);//默认的数字显示在柱子中,通过如下两句可调整数字的显示//注意:此句很关键,若无此句,那数字的显示会被覆盖,给人数字没有显示出来的问题renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));renderer.setItemLabelAnchorOffset(10D);renderer.setItemLabelFont(new Font("宋体", Font.PLAIN, 12));renderer.setItemLabelsVisible(true);//设置每个地区所包含的平行柱的之间距离//renderer.setItemMargin(0.3);plot.setRenderer(renderer);//设置地区、销量的显示位置//将下方的“肉类”放到上方plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);//将默认放在左边的“销量”放到右方plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);//String filename =ServletUtilities.saveChartAsPNG(chart, 500, 300,null, session);String graphURL = request.getContextPath()+ "/DisplayChart?filename=" + filename;%><img src="<%=graphURL%>" width=600 height=600 border=0usemap="#<%= filename %>"></body></html>显示结果:。

jFreeChart图形显示设置(柱状图)

jFreeChart图形显示设置(柱状图)
3.5f,//设置柱的Outline颜色
custombarrender3d.setSeriesOutlinePaint(0,
2.3f,
4.5f));//标签显示与设定位置的距离
custombarrender3d.setItemLabelAnchorOffset(10D);//设置每个基站所包含的平行柱的之间距离
BarRender3D是Render的一个实现类。在这个类中包含对3D柱状图的数据区的显示设置。BarRender3D含有3D背景的设置、柱体的设置、柱体间距的设置等等,例如:
//3D柱状图显示设置对象
BarRender3D render3d =newBarRender3D();// 3D坐标轴的墙体颜色
TextTitle title = chart.getTitle();
//设置chart图标题的字体
title.setFont(newFont("黑体", Font.CENTER_BASELINE, 24));//X轴字体
CategoryAxis domainAxisTemp = plot.getDomainAxis();
privateJFreeChart createChartPole(CategoryDataset dcd) {//构造基本的JFreeChart
setTitle(Title);
setXAxisTitle(x);
setYAxot = (CategoryPlot)chart.getPlot();
custombarrender3d.setSeriesItemLabelFont(1, new Font("宋体",//各柱体的宽度
custombarrender3d.setMaximumBarWidth(

用JFreeChart做JSP配置、柱形图、饼图.曲线图大全(四).docx

用JFreeChart做JSP配置、柱形图、饼图.曲线图大全(四).docx

四.曲线图接着我们来介绍曲线图的使用。

在笔者日常的开发工作中,曲线图用得最多,它可以用来绘制趋势图、统计分析等。

首先我们在WebRoot下建立一个line目录,用来存放曲线图实例的jsp页面。

我们在该目录下建立sample1.jsp页面来做一个简单的曲线图的例子。

在开始编码前,让我们来看看与画曲线图密切相关的几个类:1)TimeSeriesCollection曲线数据的集合。

2)TimeSeries曲线信息序列。

3)ChartFactory可以利用该类的createTimeSeriesChart方法来创建曲线的JFreeChart对象。

在下例中,我们显示阿蜜果的blog在2007年度各月份的访问量情况,修改后的sample1.jsp 的内容如下:<%@ page contentType="text/html;charset=GBK"%><%@ page import = "org.jfree.chart.ChartFactory,org.jfree.chart.JFreeChart,org.jfree.chart.servlet.ServletUtilities,org.jfree.chart.title.TextTitle,org.jfree.data.time.TimeSeries,org.jfree.data.time.Month,org.jfree.data.time.TimeSeriesCollection,java.awt.Font"%><%//访问量统计时间线TimeSeries timeSeries = new TimeSeries("阿蜜果blog访问量统计", Month.class);//时间曲线数据集合TimeSeriesCollection lineDataset = new TimeSeriesCollection();//构造数据集合timeSeries.add(new Month(1, 2007), 11200);timeSeries.add(new Month(2, 2007), 9000);timeSeries.add(new Month(3, 2007), 6200);timeSeries.add(new Month(4, 2007), 8200);timeSeries.add(new Month(5, 2007), 8200);timeSeries.add(new Month(6, 2007), 12200);timeSeries.add(new Month(7, 2007), 13200);timeSeries.add(new Month(8, 2007), 8300);timeSeries.add(new Month(9, 2007), 12400);timeSeries.add(new Month(10, 2007), 12500);timeSeries.add(new Month(11, 2007), 13600);timeSeries.add(new Month(12, 2007), 12500);lineDataset.addSeries(timeSeries);JFreeChart chart = ChartFactory.createTimeSeriesChart("访问量统计时间线", "月份", "访问量", lineDataset, true, true, true);//设置子标题TextTitle subtitle = new TextTitle("2007年度", new Font("黑体", Font.BOLD, 12)); chart.addSubtitle(subtitle);//设置主标题chart.setTitle(new TextTitle("阿蜜果blog访问量统计", new Font("隶书", Font.ITALIC, 15)));chart.setAntiAlias(true);String filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, null, session); String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename; %><img src="<%= graphURL %>"width=500 height=300 border=0 usemap="#<%= filename %>">运行后的曲线效果如下图所示:有时我们需要显示各数据点及其数值,这是我们需要对上例进行一点改动,在JFreeChart chart = ChartFactory.createTimeSeriesChart……后,TextTitle subtitle = new TextTitle……前加上如下的代码:XYPlot plot = (XYPlot) chart.getPlot();XYLineAndShapeRenderer xylineandshaperenderer =(XYLineAndShapeRenderer)plot.getRenderer();//设置网格背景颜色plot.setBackgroundPaint(Color.white);//设置网格竖线颜色plot.setDomainGridlinePaint(Color.pink);//设置网格横线颜色plot.setRangeGridlinePaint(Color.pink);//设置曲线图与xy轴的距离plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 10D));//设置曲线是否显示数据点xylineandshaperenderer.setBaseShapesVisible(true);//设置曲线显示各数据点的值XYItemRenderer xyitem = plot.getRenderer();xyitem.setBaseItemLabelsVisible(true);xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSI DE12, TextAnchor.BASELINE_LEFT));xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 14));plot.setRenderer(xyitem);并引入了一些另外的包,引入包的语句变成:<%@ page import = "org.jfree.chart.ChartFactory,org.jfree.chart.title.TextTitle,org.jfree.data.time.TimeSeries,org.jfree.data.time.Month,org.jfree.data.time.TimeSeriesCollection,org.jfree.chart.plot.XYPlot,org.jfree.chart.renderer.xy.XYLineAndShapeRenderer,java.awt.Color,org.jfree.ui.RectangleInsets,java.awt.Font,org.jfree.chart.renderer.xy.XYItemRenderer,org.jfree.chart.JFreeChart,org.jfree.chart.servlet.ServletUtilities,bels.*,org.jfree.ui.*"%>运行该实例,效果如下所示:上面两例的曲线图都是但曲线的,有时候我们对两个曲线进行比较,例如对阿蜜果在2006年度和2007年度的blog访问量进行比较,在此种情况下,我们需要在一个曲线图中显示两个曲线。

JfreeChart的柱状图的画法

JfreeChart的柱状图的画法

JfreeChart的柱状图的画法1:前提:需要导入Jfreechart的相关jar包主要的步骤:1.首先是类需要继承ApplicationFrame类,保证整个类可以成为一个容器;2.创建CategoryDataset数据集,为jfreechart提供数据支持;创建CategoryDataset的方法如下:DefaultCategoryDataset defaultDataset=new DefaultDataset();//添加数据defaultDataset.addValue(double realNumber,String chartName,String categoryType);参数说明:realNumber--------表示的是该种类型的真实数据是多少,也就是一个柱子上显示出来的数据chartName---------我理解的意思是任意复制的柱的名称,如果有多个数据的话(也就是多个addValue)chartName不一致的话会导致柱子间的空隙的宽度的变化,猜想是一个类型里组的性质(也就是一个type对应多个柱子,类似于统计一年里每个月几个人的信息)categoryType-------也就是具体的某个类型的标签,在上图中的体现就是Apple,banana,grape这些3.根据CategoryDataset数据集创建一个JFreeChart;创建JFreeChart的方法如下:JFreeChart jfreechart=ChartFactory.createBarChart(String desc,String leftDesc,String topDesc,CategoryDataset dataset,String direction,boolean seriesFlag,booleantooltipFlag ,boolean urlFlag);参数说明:desc---------------也就是整个图表的说明,如图中所示为“Ali’s Fruits”那一部分的描述leftDesc----------即是图表中type的说明文字topDesc----------即是图中Number的说明文字dataset-----------即是所创建的CategoryDataset数据集direction---------表示图表生成的方向,使用seriesFlag--------表示是否显示显示下面的种类如箭头所指,这里也可以理解在addValue的时候设这的CategoryName的名字的用处了,用于多个颜色的区分toolTipFlag----------表示是否启用鼠标放到柱子上的提示信息urlFlag---------------表示是否启用url网址,但没用过4.根据JFreeChart构建一个ChartPanel容器用于盛放JFreeChart;创建ChartPanel的步骤如下:ChartPanel chartPanel=new ChartPanel(JFreeChart jfreechart);5.最后,把包含有JFreeChart的ChartPanel放入到ApplicationFrame中去把ChartPanel放入到ApplicationFrame中去也就是把组件放入到容器中去,值得一提的是向Jframe或者这里的ApplicationFrame中添加组件的方式有两种:(1)用getContentPane()方法获取Frame的内容面板,再加入组件(2)建立一个Jpanel或者是JdesktopPane之类的中间容器,把组件添加到这个中间容器中去,用setContentPane()方法把容器放入到Frame中Eg: JPanel contentPanel=new Jpanel(jfreechart);frame.setCotentPane(contentPane);//如果类继承了ApplicationFrame 等父类,那么可以直接使用setContentPane(contentPane)而省略掉frame6.测试运行详细的例子见下一篇文章。

jFreeChart图形显示设置(柱状图)

jFreeChart图形显示设置(柱状图)

jFreeChart图形显示设置(柱状图)说明表源代码://BarRenderer3Dprivate JFreeChart createChartPole(CategoryDataset dcd) { // 构造基本的JFreeChartsetTitle(Title);setXAxisTitle(x);setYAxisTitle(y);JFreeChart chart = ChartFactory.createBarChart3D(getTitle(), getXAxisTitle(), getYAxisTitle(), dcd,PlotOrientation.VERTICAL, true, true, false);CategoryPlot plot = (CategoryPlot)chart.getPlot();BarRenderer3D custombarrenderer3d = new BarRenderer3D();//设置图例LegendTitle legtitle = chart.getLegend();//设置图例字体legtitle.setItemFont(new Font("黑体", Font.ROMAN_BASELINE, 15));//取得chart图的标题TextTitle title = chart.getTitle();//设置chart图标题的字体title.setFont(new Font("黑体", Font.CENTER_BASELINE, 24));//X轴字体CategoryAxis domainAxisTemp = plot.getDomainAxis();domainAxisTemp.setLabelFont(new Font("黑体", Font.ROMAN_BASELINE, 12));//设置x轴各项标题的字体domainAxisTemp.setTickLabelFont(new Font("黑体",Font.ROMAN_BASELINE, 12));domainAxisTemp.setTickLabelPaint(Color.BLUE);//Y轴字体ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(new Font("黑体", Font.ROMAN_BASELINE, 12));//custombarrenderer3d.setBaseOutlinePaint(Color.blue);custombarrenderer3d.setWallPaint(Color.lightGray);// 3D坐标轴的墙体颜色custombarrenderer3d.setMinimumBarLength(0.01);custombarrenderer3d.setMaximumBarWidth(0.05);//控制X轴坐标点文字角度当X轴的坐标点超过15个时,文字角度调整为45度向上if(dcd.getColumnCount() > 8){chart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions (CategoryLabelPositions.DOWN_45);// 设置坐标点标记与坐标轴之间的距离//jfreechart.getCategoryPlot().getDomainAxis().setCategoryLabelPosi tionOffset(50);//jf.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(Ca tegoryLabelPositions.createUpRotationLabelPositions(Math.PI/6));}// 显示每个柱的数值,并修改该数值的字体属性<BR>custombarrenderer3d.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());// custombarrenderer3d.setBaseItemLabelFont(new Font("黑体", Font.ROMAN_BASELINE, 12));custombarrenderer3d.setBaseItemLabelFont(new Font("黑体", Font.CENTER_BASELINE, 15));//是否显示柱的数值标签custombarrenderer3d.setBaseItemLabelsVisible(true);// 每个柱的数值,标签显示的方式及位置custombarrenderer3d.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_CENTER));// 标签显示与设定位置的距离custombarrenderer3d.setItemLabelAnchorOffset(10D);// 设置每个基站所包含的平行柱的之间距离custombarrenderer3d.setItemMargin(0.05D);// 设置柱的颜色custombarrenderer3d.setSeriesPaint(0,Color.getHSBColor(3.5f, 2.3f, 4.5f));// 设置柱的 Outline 颜色custombarrenderer3d.setSeriesOutlinePaint(0, Color.BLACK);//为单个柱体设置字体,"1"为柱体的序号// custombarrenderer3d.setSeriesItemLabelFont(1, new Font("宋体", Font.CENTER_BASELINE, 72));// 各柱体的宽度custombarrenderer3d.setMaximumBarWidth(0.050000000000000003D);plot.setRenderer(custombarrenderer3d);return chart;}。

jfreechart线形图和柱状图同时显示

jfreechart线形图和柱状图同时显示

jfreechart线形图和柱状图同时显示jfreechart实例线形图和柱状图同时显示package com.ami;import org.jfree.ui.ApplicationFrame;import java.awt.Color;import java.awt.Dimension;import java.text.NumberFormat;import javax.swing.JPanel;import org.jfree.chart.*;import org.jfree.chart.axis.*;import org.jfree.chart.plot.*;importorg.jfree.chart.renderer.category.LineAndShapeRenderer;import org.jfree.chart.title.TextTitle;import org.jfree.data.DataUtilities;import org.jfree.data.DefaultKeyedValues;import org.jfree.data.category.CategoryDataset;import org.jfree.data.general.DatasetUtilities;import org.jfree.ui.ApplicationFrame;import org.jfree.ui.RefineryUtilities;import org.jfree.util.SortOrder;public class ParetoChartDemo1 extends ApplicationFrame {public ParetoChartDemo1(String s){super(s);JPanel jpanel = createDemoPanel();jpanel.setPreferredSize(new Dimension(550, 270));setContentPane(jpanel);}public static JFreeChart createChart(CategoryDataset acategorydataset[]){JFreeChart jfreechart = ChartFactory.createBarChart("Freshmeat Software Projects", "Language", "Projects", acategorydataset[0], PlotOrientation.VERTICAL, true, true, false);jfreechart.addSubtitle(new TextTitle("By Programming Language"));jfreechart.addSubtitle(new TextTitle("As at 5 March 2003"));jfreechart.setBackgroundPaint(Color.white);CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();categoryplot.setBackgroundPaint(Color.lightGray);categoryplot.setRangeGridlinePaint(Color.white);CategoryAxis categoryaxis = categoryplot.getDomainAxis();categoryaxis.setLowerMargin(0.02D);categoryaxis.setUpperMargin(0.02D);categoryaxis.setCategoryLabelPositions(CategoryLabelPositi ons.UP_90);NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();numberaxis.setStandardTickUnits(NumberAxis.createInteger TickUnits());LineAndShapeRenderer lineandshaperenderer = new LineAndShapeRenderer();NumberAxis numberaxis1 = new NumberAxis("Percent");numberaxis1.setNumberFormatOverride(NumberFormat.ge tPercentInstance());categoryplot.setRangeAxis(1, numberaxis1);categoryplot.setDataset(1, acategorydataset[1]);categoryplot.setRenderer(1, lineandshaperenderer);categoryplot.mapDatasetToRangeAxis(1, 1);categoryplot.setDatasetRenderingOrder(DatasetRendering Order.FORWARD);return jfreechart;}public static CategoryDataset[] createDatasets(){DefaultKeyedValues defaultkeyedvalues = new DefaultKeyedValues();defaultkeyedvalues.addValue("C", new Integer(4843));defaultkeyedvalues.addValue("C++", new Integer(2098));defaultkeyedvalues.addValue("C#", new Integer(26));defaultkeyedvalues.addValue("Java", new Integer(1901));defaultkeyedvalues.addValue("Perl", new Integer(2507));defaultkeyedvalues.addValue("PHP", new Integer(1689));defaultkeyedvalues.addValue("Python", new Integer(948));defaultkeyedvalues.addValue("Ruby", new Integer(100));defaultkeyedvalues.addValue("SQL", new Integer(263));defaultkeyedvalues.addValue("Unix Shell", new Integer(485));defaultkeyedvalues.sortByValues(SortOrder.DESCENDING);org.jfree.data.KeyedValues keyedvalues = DataUtilities.getCumulativePercentages(defaultkeyedvalues);CategoryDataset categorydataset = DatasetUtilities.createCategoryDataset("Languages", defaultkeyedvalues);CategoryDataset categorydataset1 = DatasetUtilities.createCategoryDataset("Cumulative",keyedvalues);return (new CategoryDataset[] {categorydataset, categorydataset1});}public static JPanel createDemoPanel(){CategoryDataset acategorydataset[] = createDatasets();JFreeChart jfreechart = createChart(acategorydataset);return new ChartPanel(jfreechart);}public static void main(String args[]){ParetoChartDemo1 paretochartdemo1 = new ParetoChartDemo1("Pareto Chart Demo 1");paretochartdemo1.pack();RefineryUtilities.centerFrameOnScreen(paretochartdemo1);paretochartdemo1.setVisible(true);}}效果图。

jFreeChart柱形图

jFreeChart柱形图

jFreeChart柱形图JFreeChart柱状图以下是源代码:/**jfreechart***/package .terje.jfreechart;import java.awt.Font;import java.io.File;import java.io.IOException;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart; importorg.jfree.chart.axis.CategoryAxis; importorg.jfree.chart.axis.ValueAxis;import bels.ItemLabelAnchor;import bels.ItemLabelPosition;importor;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.TextAnchor;/*** **@author terje liu*/public class DomeOne{public static void main(String[] args)throws IOException{JFreeChart chart = ChartFactory.createBarChart("桂林甜点供给(个)", "城区 ","供给量 ", getDateSet(),PlotOrientation.HORIZONTAL, true, true,false);//--------- 显示中文 ------------\\chart.getTitle().setFont(new Font(" 宋体 ",Font.PLAIN, 20));CategoryPlot plot = chart.getCategoryPlot();// 设置分类中文,就是图片里面的那个"城区 "和"xx 区"CategoryAxis cgAxis = plot.getDomainAxis();cgAxis.setTickLabelFont(new Font(" 宋体 ",Font.PLAIN, 11));cgAxis.setLabelFont(new Font("宋体", Font.PLAIN, 15));//设置数值中文ValueAxis vAxis = plot.getRangeAxis();vAxis.setTickLabelFont(new Font(" 宋体 ",Font.PLAIN, 11));vAxis.setLabelFont(new Font("宋体", Font.PLAIN, 15));//显示说明中文chart.getLegend().setItemFont(new Font(" 宋体 ", Font.PLAIN, 16));//------- 微调整 -------\\//设置边距,右侧的(防备最大值,跑到图片外面去,因此要设置一下)vAxis.setUpperMargin(0.08);//设置最小值(有个最小值好一些,简单突出要点嘛)vAxis.setLowerBound(200);//------ 将每个柱子显示的数值显示出来 ---------\\BarRenderer barRender = new BarRenderer();barRender.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());barRender.setBaseItemLabelFont(new Font("宋体", Font.PLAIN, 11));barRender.setBaseItemLabelsVisible(true);//防止由于数值过小,显示不显然,或则看不到barRender.setMinimumBarLength(10);plot.setRenderer(barRender);//调理柱子显示的数值的地点//经过设置 ItemLabelPosition 里面的 2 个静态参数(奇异了, ItemLabelAnchor 的含义文档仿佛没有怎么说)barRender.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE2, TextAnchor.TOP_LEFT));//------ 将结果以图片形式输出 ------\\ File f =new File("c:\\domeone.jpg");ChartUtilities.saveChartAsJPEG(f, chart, 800, 640);}/***数据集**/public static CategoryDataset getDateSet(){DefaultCategoryDataset dcd = new DefaultCategoryDataset();dcd.addValue(552, " 布丁 ", " 七星高新区 ");dcd.addValue(1131, " 蛋挞 ", " 七星高新区 ");dcd.addValue(912, " 海苔饼 ", " 七星高新区 ");dcd.addValue(513, " 脆皮奶 ", " 七星高新区 ");dcd.addValue(313, " 巧克力蛋糕 ", " 七星高新区 ");dcd.addValue(946, " 布丁 ", " 秀峰区 ");dcd.addValue(563, " 蛋挞 ", " 秀峰区 ");dcd.addValue(712, " 海苔饼 ", " 秀峰区 ");dcd.addValue(399, " 脆皮奶 ", " 秀峰区 ");dcd.addValue(299, " 巧克力蛋糕 ", " 秀峰区 ");dcd.addValue(564, " 布丁 ", " 象山区 ");dcd.addValue(765, " 蛋挞 ", " 象山区 ");dcd.addValue(592, " 海苔饼 ", " 象山区 ");dcd.addValue(799, " 脆皮奶 ", " 象山区 ");dcd.addValue(499, " 巧克力蛋糕 ", " 象山区 ");dcd.addValue(464, " 布丁 ", " 叠彩区 ");dcd.addValue(263, " 蛋挞 ", " 叠彩区 ");dcd.addValue(992, " 海苔饼 ", " 叠彩区 ");dcd.addValue(691, " 脆皮奶 ", " 叠彩区 ");dcd.addValue(291, " 巧克力蛋糕 ", " 叠彩区 ");dcd.addValue(261, " 布丁 ", " 雁山区 ");dcd.addValue(333, " 蛋挞 ", " 雁山区 ");dcd.addValue(594, " 海苔饼 ", " 雁山区 ");dcd.addValue(599, " 脆皮奶 ", " 雁山区 ");dcd.addValue(201, " 巧克力蛋糕 ", " 雁山区 ");return dcd;}}此刻展望一个需求,用户不需要在柱子弹上方显示数字,而是显示百分比。

JavaJFreeChart柱状图单组柱子的不同颜色显示

JavaJFreeChart柱状图单组柱子的不同颜色显示

Java JFreeChart柱状图单组柱子的不同颜色显示JFreeChart 柱状图中单组柱子用不同颜色来显示的实现方法是自定义一个Renderer 来继承BarRenderer类,然后重载getItemPaint(int i,int j)方法。

实现效果如下:实现代码如下:[html]view plain copy1.public class CustomRenderer extends org.jfree.chart.renderer.category.BarRenderer {2.3./**4.*5.*/6.private static final long serialVersionUID= 784630226449158436L ;7.private Paint[] colors;8.//初始化柱子颜色9.private String[]colorValues= { "#AFD8F8", "#F6BD0F", "#8BBA00", "#FF8E46", "#008E8E", "#D64646" };10.11.public CustomRenderer() {12.colors= new Paint[colorValues.length];13.for (int i = 0; i< colorValues.length; i++) {14.colors[i] = Color.decode(colorValues[i]);15.}16.}17.18.//每根柱子以初始化的颜色不断轮循19.public Paint getItemPaint(int i, int j) {20.return colors[j % colors.length];21.}22.}[html]view plain copy1.public class CreateJFreeChartBarColor {2.3./**4.*创建JFreeChart Bar Chart(柱状图)5.*/6.public static void main(String[] args) {7.//步骤 1:创建 CategoryDataset对象(准备数据)8.CategoryDataset dataset = createDataset ();9.//步骤2:根据Dataset生成JFreeChart对象,以及做相应的设置10.JFreeChart freeChart= createChart (dataset);11.//步骤3:将JFreeChart对象输出到文件,Servlet输出流等12.saveAsFile(freeChart, "E:\\bar.png", 500, 400);13.}14.15.//保存为文件16.public static void saveAsFile(JFreeChart chart, String outputPath, int weight, int height) {17.FileOutputStream out = null ;18.try {19.File outFile=new File(outputPath);20.if (!outFile.getParentFile().exists()) {21.outFile.getParentFile().mkdirs();22.}23.out = new FileOutputStream(outputPath);24.//保存为PNG文件25.ChartUtilities.writeChartAsPNG(out, chart, weight, height);26.out.flush();27.} catch (FileNotFoundException e) {28. e.printStackTrace();29.} catch (IOException e) {30. e.printStackTrace();31.} finally {32.if (out != null) {33.try {34.out.close();35.} catch (IOException e) {36.// do nothing37.}38.}39.}40.}41.42.//根据CategoryDataset生成JFreeChart对象43.public static JFreeChart createChart(CategoryDataset categoryDataset) {44.JFreeChart jfreechart= ChartFactory.createBarChart("学生统计图", //标题45."学生姓名 ", // categoryAxisLabel(category轴,横轴,X 轴的标签)46."年龄 ", // valueAxisLabel( value 轴,纵轴, Y 轴的标签)47.categoryDataset, // dataset48.PlotOrientation.VERTICAL, false, // legend49.false, // tooltips50.false); // URLs51.52.Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);53.54.jfreechart.setTextAntiAlias(false);55.jfreechart.setBackgroundPaint(Color.white);56.57.CategoryPlot plot = jfreechart.getCategoryPlot();//获得图表区域对象58.59.//设置横虚线可见60.plot.setRangeGridlinesVisible(true);61.//虚线色彩62.plot.setRangeGridlinePaint(Color.gray);63.//数据轴精度64.NumberAxis vn = (NumberAxis) plot.getRangeAxis();65.// vn.setAutoRangeIncludesZero(true);66.DecimalFormat df = new DecimalFormat("#0.0");67.vn.setNumberFormatOverride(df); //数据轴数据标签的显示格式68.69.// x轴设置70.CategoryAxis domainAxis= plot .getDomainAxis();71.domainAxis.setLabelFont(labelFont);//轴标题72.domainAxis.setTickLabelFont(labelFont);//轴数值73.// Lable( Math.PI/3.0)度倾斜74.// domainAxis.setCategoryLabelPositions(CategoryLabelPositions75.// .createUpRotationLabelPositions(Math.PI / 3.0));76.domainAxis.setMaximumCategoryLabelWidthRatio(6.00f);//横轴上的 Lable77.//是否完整显示78.79.//设置距离图片左端距离80.domainAxis.setLowerMargin(0.1);81.//设置距离图片右端距离82.domainAxis.setUpperMargin(0.1);83.//设置columnKey是否间隔显示84.// domainAxis.setSkipCategoryLabelsToFit(true);85.plot.setDomainAxis(domainAxis);86.//设置柱图背景色(注意,系统取色的时候要使用16 位的模式来查看颜色编码,这样比较准确)87.plot.setBackgroundPaint(new Color(255, 255, 204));88.89.// y轴设置90.ValueAxis rangeAxis = plot .getRangeAxis();91.rangeAxis.setLabelFont(labelFont);92.rangeAxis.setTickLabelFont(labelFont);93.//设置最高的一个Item与图片顶端的距离94.rangeAxis.setUpperMargin(0.15);95.//设置最低的一个Item与图片底端的距离96.rangeAxis.setLowerMargin(0.15);97.plot.setRangeAxis(rangeAxis);98.99.//解决中文乱码问题(关键)100.TextTitle textTitle= jfreechart.getTitle();101.textTitle.setFont(new Font("黑体 ", Font.PLAIN, 20));102.domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));103.domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));104.vn.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));105.vn.setLabelFont(new Font("黑体 ", Font.PLAIN, 12));106.// jfreechart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));107.108.//使用自定义的渲染器109.CustomRenderer renderer= new CustomRenderer();110.//设置柱子宽度111.renderer.setMaximumBarWidth(0.2);112.//设置柱子高度113.renderer.setMinimumBarLength(0.2);114.//设置柱子边框颜色115.renderer.setBaseOutlinePaint(Color.BLACK);116.//设置柱子边框可见117.renderer.setDrawBarOutline(true);118.//设置每个地区所包含的平行柱的之间距离119.renderer.setItemMargin(0.5);120.jfreechart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIA SING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);121.//显示每个柱的数值,并修改该数值的字体属性122.renderer.setIncludeBaseInRange(true);123.renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());124.renderer.setBaseItemLabelsVisible(true);125.plot.setRenderer(renderer);126.//设置柱的透明度127.plot.setForegroundAlpha(1.0f);128.129.//背景色透明度130.plot.setBackgroundAlpha(0.5f);131.132.return jfreechart;133.}134.135.//创建CategoryDataset对象136.public static CategoryDataset createDataset() {137.double[][]data= new double[][] { { 25, 24, 40, 12, 33, 33 } };138.String[]rowKeys={""};139.String[]columnKeys = { "张三","李四","王五","马六","陈七","赵八" };140.CategoryDataset dataset= DatasetUtilities.createCategoryDataset(ro wKeys, columnKeys, data);141.return dataset;142.}143.144.}。

jfreechart完整柱状图

jfreechart完整柱状图

JFreechart完整柱状图import class AttendanceMain{p ublic static void main(String[] args) throws IOException{double[][] data = new double[][]{{100,96,98,95,99,100,92,93,91,94,96},{97,96,98,95,99,100,92,93,91,94,96},{97,96,98,95,99,100,92,93,91,94,96},{97,96,98,95,99,100,92,93,91,94,96}};String[] columnKeys = { "测控1班", "测控2班", "信号1班", "信号2班", "信号3班" ,"计通1班","计通2班","城轨1班","城轨2班","计应1班","计应2班"};String[] rowKeys = {"2021级","2021级","2021级","2021级"};new A ttendance(data,rowKeys,columnKeys );ut,;etItemFont(new Font("华文行楷",,20));//设置上下左右显示位置;;//这句代码解决了底部汉字乱码的问题(new Font("华文行楷",,20));//显示每一个柱的数值,并修改该数值的字体属性(new StandardCategoryItemLabelGenerator());//显示每一个柱的数值(true);//注意:此句很关键,若无此句,那数字的显示会被覆盖,给人数字没有显示出来的问题//(new ItemLabelPosition( , );(10D);// 设置柱形图上的文字偏离值//(true);(render);//利用咱们设计的效果//设置纵横坐标的显示位置//学校显示在下端(柱子竖直)或左侧(柱子水平);//人数显示在下端(柱子水平)或左侧(柱子竖直);//设定柱子上面的颜色(0, ; // 给series1 Bar(1, ("#8979FF")); // 给series2 Bar(2, ; // 给series4 Bar(3, new Color(200, 50, 50)); // 给series5 Bar(0,;//边框为黑色(1,;//边框为黑色(2,; //边框为黑色(3,;//边框为黑色FileOutputStream gf = null;try{gf = new F ileOutputStream("E:\\");//将报表保留为JPG文件(gf, //文件保留物理路径包括路径和文件名1f, //图片质量chart, //图表对象1600, //图像宽度668, //图像高度null); //显示信息}finally{try{//关闭输出流();"success");}catch(Exception e){}}}}。

java利用JFreeChart实现各种数据统计图(柱形图,饼图,折线图)

java利用JFreeChart实现各种数据统计图(柱形图,饼图,折线图)

java利⽤JFreeChart实现各种数据统计图(柱形图,饼图,折线图)最近在做数据挖掘的课程设计,需要将数据分析的结果很直观的展现给⽤户,这就要⽤到数据统计图,要实现这个功能就需要⼏个第三⽅包了:1. jfreechart-1.0.13.jar2. jcommon-1.0.16.jar3. gnujaxp.jar先来看⼀下,最终效果图:主要是jfreechart-1.0.13.jar,但这三个包要齐全,我已经将所有与jfreechart有关的jar包与本⽂实例的⼯程(代码)⼀同压缩上传了,有兴趣的同学可以下载,接下来,我们⼀步步来实现本程序。

1,建,⽴java项⽬,在这个项⽬在建⽴⼀个新的⽂件夹lib;2,将上述三个jar包,复制到lib3,然后右键点击这个java项⽬,选择Properties4,在左侧列表⾥选中Java Build Path,右侧选中Libraries5,点击Add JARs6,然后去选择这个项⽬中lib⽂件夹中的三个jar,点击确定成功后,项⽬中会多⼀个⽂件夹为:Referenced Libraries⼆,实现柱形图的java代码:import java.awt.Font;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.CategoryAxis;import org.jfree.chart.axis.ValueAxis;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset;public class BarChart {ChartPanel frame1;public BarChart(){CategoryDataset dataset = getDataSet();JFreeChart chart = ChartFactory.createBarChart3D("⽔果", // 图表标题"⽔果种类", // ⽬录轴的显⽰标签"数量", // 数值轴的显⽰标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表⽅向:⽔平、垂直true, // 是否显⽰图例(对于简单的柱状图必须是false)false, // 是否⽣成⼯具false // 是否⽣成URL链接);//从这⾥开始CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象CategoryAxis domainAxis=plot.getDomainAxis(); //⽔平底部列表domainAxis.setLabelFont(new Font("⿊体",Font.BOLD,14)); //⽔平底部标题domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状rangeAxis.setLabelFont(new Font("⿊体",Font.BOLD,15));chart.getLegend().setItemFont(new Font("⿊体", Font.BOLD, 15));chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体//到这⾥结束,虽然代码有点多,但只为⼀个⽬的,解决汉字乱码问题frame1=new ChartPanel(chart,true); //这⾥也可以⽤chartFrame,可以直接⽣成⼀个独⽴的Frame}private static CategoryDataset getDataSet() {DefaultCategoryDataset dataset = new DefaultCategoryDataset();dataset.addValue(100, "北京", "苹果");dataset.addValue(100, "上海", "苹果");dataset.addValue(100, "⼴州", "苹果");dataset.addValue(200, "北京", "梨⼦");dataset.addValue(200, "上海", "梨⼦");dataset.addValue(200, "⼴州", "梨⼦");dataset.addValue(300, "北京", "葡萄");dataset.addValue(300, "上海", "葡萄");dataset.addValue(300, "⼴州", "葡萄");dataset.addValue(400, "北京", "⾹蕉");dataset.addValue(400, "上海", "⾹蕉");dataset.addValue(400, "⼴州", "⾹蕉");dataset.addValue(500, "北京", "荔枝");dataset.addValue(500, "上海", "荔枝");dataset.addValue(500, "⼴州", "荔枝");return dataset;}public ChartPanel getChartPanel(){return frame1;}}效果图如下:但我们把private static CategoryDataset getDataSet(){}⽅法中的数据变化⼀下后,⼜会形成另⼀种效果,⽐如说我们改成:private static CategoryDataset getDataSet() {DefaultCategoryDataset dataset = new DefaultCategoryDataset();dataset.addValue(100, "苹果", "苹果");dataset.addValue(200, "梨⼦", "梨⼦");dataset.addValue(300, "葡萄", "葡萄");dataset.addValue(400, "⾹蕉", "⾹蕉");dataset.addValue(500, "荔枝", "荔枝");return dataset;}效果图如下:三,实现饼状图的java代码:package com.njue.testJFreeChart;import java.awt.Font;import java.text.DecimalFormat;import java.text.NumberFormat;import javax.swing.JPanel;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.JFreeChart;import bels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot;import org.jfree.data.general.DefaultPieDataset;public class PieChart {ChartPanel frame1;public PieChart(){DefaultPieDataset data = getDataSet();JFreeChart chart = ChartFactory.createPieChart3D("⽔果产量",data,true,false,false);//设置百分⽐PiePlot pieplot = (PiePlot) chart.getPlot();DecimalFormat df = new DecimalFormat("0.00%");//获得⼀个DecimalFormat对象,主要是设置⼩数问题NumberFormat nf = NumberFormat.getNumberInstance();//获得⼀个NumberFormat对象StandardPieSectionLabelGenerator sp1 = new StandardPieSectionLabelGenerator("{0} {2}", nf, df);//获得StandardPieSectionLabelGenerator对象 pieplot.setLabelGenerator(sp1);//设置饼图显⽰百分⽐//没有数据的时候显⽰的内容pieplot.setNoDataMessage("⽆数据显⽰");pieplot.setCircular(false);pieplot.setLabelGap(0.02D);pieplot.setIgnoreNullValues(true);//设置不显⽰空值pieplot.setIgnoreZeroValues(true);//设置不显⽰负值frame1=new ChartPanel (chart,true);chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体PiePlot piePlot= (PiePlot) chart.getPlot();//获取图表区域对象piePlot.setLabelFont(new Font("宋体",Font.BOLD,10));//解决乱码chart.getLegend().setItemFont(new Font("⿊体",Font.BOLD,10));}private static DefaultPieDataset getDataSet() {DefaultPieDataset dataset = new DefaultPieDataset();dataset.setValue("苹果",100);dataset.setValue("梨⼦",200);dataset.setValue("葡萄",300);dataset.setValue("⾹蕉",400);dataset.setValue("荔枝",500);return dataset;}public ChartPanel getChartPanel(){return frame1;}}效果图如下:四,实现折线图的java代码:package com.njue.testJFreeChart;import java.awt.Font;import java.text.SimpleDateFormat;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.DateAxis;import org.jfree.chart.axis.ValueAxis;import org.jfree.chart.plot.XYPlot;import org.jfree.data.time.Month;import org.jfree.data.time.TimeSeries;import org.jfree.data.time.TimeSeriesCollection;import org.jfree.data.xy.XYDataset;public class TimeSeriesChart {ChartPanel frame1;public TimeSeriesChart(){XYDataset xydataset = createDataset();JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("Legal & General单位信托基⾦价格", "⽇期", "价格",xydataset, true, true, true);XYPlot xyplot = (XYPlot) jfreechart.getPlot();DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();dateaxis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));frame1=new ChartPanel(jfreechart,true);dateaxis.setLabelFont(new Font("⿊体",Font.BOLD,14)); //⽔平底部标题dateaxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题ValueAxis rangeAxis=xyplot.getRangeAxis();//获取柱状rangeAxis.setLabelFont(new Font("⿊体",Font.BOLD,15));jfreechart.getLegend().setItemFont(new Font("⿊体", Font.BOLD, 15));jfreechart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体}private static XYDataset createDataset() { //这个数据集有点多,但都不难理解 TimeSeries timeseries = new TimeSeries("legal & general欧洲指数信任", org.jfree.data.time.Month.class);timeseries.add(new Month(2, 2001), 181.80000000000001D);timeseries.add(new Month(3, 2001), 167.30000000000001D);timeseries.add(new Month(4, 2001), 153.80000000000001D);timeseries.add(new Month(5, 2001), 167.59999999999999D);timeseries.add(new Month(6, 2001), 158.80000000000001D);timeseries.add(new Month(7, 2001), 148.30000000000001D);timeseries.add(new Month(8, 2001), 153.90000000000001D);timeseries.add(new Month(9, 2001), 142.69999999999999D);timeseries.add(new Month(10, 2001), 123.2D);timeseries.add(new Month(11, 2001), 131.80000000000001D);timeseries.add(new Month(12, 2001), 139.59999999999999D);timeseries.add(new Month(1, 2002), 142.90000000000001D);timeseries.add(new Month(2, 2002), 138.69999999999999D);timeseries.add(new Month(3, 2002), 137.30000000000001D);timeseries.add(new Month(4, 2002), 143.90000000000001D);timeseries.add(new Month(5, 2002), 139.80000000000001D);timeseries.add(new Month(6, 2002), 137D);timeseries.add(new Month(7, 2002), 132.80000000000001D);TimeSeries timeseries1 = new TimeSeries("legal & general英国指数信任", org.jfree.data.time.Month.class);timeseries1.add(new Month(2, 2001), 129.59999999999999D);timeseries1.add(new Month(3, 2001), 123.2D);timeseries1.add(new Month(4, 2001), 117.2D);timeseries1.add(new Month(5, 2001), 124.09999999999999D);timeseries1.add(new Month(6, 2001), 122.59999999999999D);timeseries1.add(new Month(7, 2001), 119.2D);timeseries1.add(new Month(8, 2001), 116.5D);timeseries1.add(new Month(9, 2001), 112.7D);timeseries1.add(new Month(10, 2001), 101.5D);timeseries1.add(new Month(11, 2001), 106.09999999999999D);timeseries1.add(new Month(12, 2001), 110.3D);timeseries1.add(new Month(1, 2002), 111.7D);timeseries1.add(new Month(2, 2002), 111D);timeseries1.add(new Month(3, 2002), 109.59999999999999D);timeseries1.add(new Month(4, 2002), 113.2D);timeseries1.add(new Month(5, 2002), 111.59999999999999D);timeseries1.add(new Month(6, 2002), 108.8D);timeseries1.add(new Month(7, 2002), 101.59999999999999D);TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(); timeseriescollection.addSeries(timeseries);timeseriescollection.addSeries(timeseries1);return timeseriescollection;}public ChartPanel getChartPanel(){return frame1;}}效果图如下:再来看⼀下主⽅法:import java.awt.GridLayout;import javax.swing.JFrame;public class mainClass {public static void main(String args[]){JFrame frame=new JFrame("Java数据统计图");frame.setLayout(new GridLayout(2,2,10,10));frame.add(new BarChart().getChartPanel()); //添加柱形图frame.add(new BarChart1().getChartPanel()); //添加柱形图的另⼀种效果 frame.add(new PieChart().getChartPanel()); //添加饼状图frame.add(new TimeSeriesChart().getChartPanel()); //添加折线图frame.setBounds(50, 50, 800, 600);frame.setVisible(true);}}五,总结以上都是⼀个简单的例⼦去实现了,想了解更深的同学可⾃⾏查询资料,其实以上代码都通俗易懂,只要结合⾃⼰的实际情况,便可开发出属于⾃⼰的Application,⼤家可以看出我这⾥是在Application上实现的,其实更多情况数据统计图在javaweb上应⽤更多,⼤家也可⾃⾏了解。

Jfreechart开发手记(一)完整的柱状图-含数据下钻的实现方法

Jfreechart开发手记(一)完整的柱状图-含数据下钻的实现方法

Jfreechart开发手记(一)完整的柱状图-含数据下钻的实现
方法
Jfreechart开发手记(一)
完整的柱状图
(含数据下钻的实现)
作者:Steel.Ma
Mail:****************
****************
MSN:*************************
Blog: /steelma
/iamsteelma
1概述
本笔记阐述的是如何使用开源的Jfreechart框架,制作一个完整的柱状图并实现BI软件中常见的“数据下钻”功能。

先来看看效果图:
以上就是本笔记的范例代码所要实现的,其中,点击每根柱子,还能自动链接到另外一个页面中,并该柱所带的参数传递过去。

以下开始进行环境配置:
2环境准备与基本配置
环境选型:
Tomcat 6.0.18
Jfreechart 1.0.13
MyEclipse
Tomcat、MyEclipse可以忽略,按照默认配置即可,这里介绍下如何配置
Jfreechart的包。

打开MyEclipse,在项目名称上右击,然后选择Build Path->Configure Build Path,将Jfreechart下的lib文件夹中的jcommon-1.0.16.jar与jfreechart-1.0.13.jar引入,注意!其他文件不要引入!切切!
引入后,效果当如下:
最后打开web.xml文件,加入如下这2段xml配制代码:This is the description of my J2EE
component。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

jFreeChart柱形图JFreeChart 柱状图以下是源代码:/** jfreechart** */package .terje.jfreechart;import java.awt.Font;import java.io.File;import java.io.IOException;import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis;import bels.ItemLabelAnchor;import bels.ItemLabelPosition;importbels.StandardCategoryItemLabelGenerat or;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.TextAnchor;/*** ** @author terje liu*/public class DomeOne{public static void main(String[] args) throws IOException{JFreeChart chart = ChartFactory.createBarChart("桂林甜点供应(个)", "城区","供应量", getDateSet(), PlotOrientation.HORIZONTAL, true, true,false);// ---------显示中文------------\\chart.getTitle().setFont(new Font("宋体",Font.PLAIN, 20));CategoryPlot plot = chart.getCategoryPlot();// 设置分类中文,就是图片里面的那个"城区"和"xx 区"CategoryAxis cgAxis = plot.getDomainAxis();cgAxis.setTickLabelFont(new Font("宋体",Font.PLAIN, 11));cgAxis.setLabelFont(new Font("宋体", Font.PLAIN, 15));// 设置数值中文ValueAxis vAxis = plot.getRangeAxis();vAxis.setTickLabelFont(new Font("宋体",Font.PLAIN, 11));vAxis.setLabelFont(new Font("宋体", Font.PLAIN, 15));// 显示说明中文chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 16));// -------微调整-------\\// 设置边距,右边的(防止最大值,跑到图片外面去,所以要设置一下)vAxis.setUpperMargin(0.08);// 设置最小值(有个最小值好一些,容易突出重点嘛)vAxis.setLowerBound(200);// ------将每个柱子显示的数值显示出来---------\\BarRenderer barRender = new BarRenderer();barRender.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());barRender.setBaseItemLabelFont(new Font("宋体", Font.PLAIN, 11));barRender.setBaseItemLabelsVisible(true);// 避免因为数值过小,显示不明显,或则看不到barRender.setMinimumBarLength(10);plot.setRenderer(barRender);// 调节柱子显示的数值的位置// 通过设置ItemLabelPosition里面的2个静态参数(奇怪了,ItemLabelAnchor的含义文档好像没有怎么说)barRender.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE2, TextAnchor.TOP_LEFT));// ------将结果以图片形式输出------\\File f = new File("c:\\domeone.jpg");ChartUtilities.saveChartAsJPEG(f, chart, 800, 640);}/*** 数据集**/public static CategoryDataset getDateSet(){DefaultCategoryDataset dcd = new DefaultCategoryDataset();dcd.addValue(552, "布丁", "七星高新区");dcd.addValue(1131, "蛋挞", "七星高新区");dcd.addValue(912, "海苔饼", "七星高新区");dcd.addValue(513, "脆皮奶", "七星高新区");dcd.addValue(313, "巧克力蛋糕", "七星高新区");dcd.addValue(946, "布丁", "秀峰区");dcd.addValue(563, "蛋挞", "秀峰区");dcd.addValue(712, "海苔饼", "秀峰区");dcd.addValue(399, "脆皮奶", "秀峰区");dcd.addValue(299, "巧克力蛋糕", "秀峰区");dcd.addValue(564, "布丁", "象山区");dcd.addValue(765, "蛋挞", "象山区");dcd.addValue(592, "海苔饼", "象山区");dcd.addValue(799, "脆皮奶", "象山区");dcd.addValue(499, "巧克力蛋糕", "象山区");dcd.addValue(464, "布丁", "叠彩区");dcd.addValue(263, "蛋挞", "叠彩区");dcd.addValue(992, "海苔饼", "叠彩区");dcd.addValue(691, "脆皮奶", "叠彩区");dcd.addValue(291, "巧克力蛋糕", "叠彩区");dcd.addValue(261, "布丁", "雁山区");dcd.addValue(333, "蛋挞", "雁山区");dcd.addValue(594, "海苔饼", "雁山区");dcd.addValue(599, "脆皮奶", "雁山区");dcd.addValue(201, "巧克力蛋糕", "雁山区");return dcd;}}现在预测一个需求,用户不需要在柱子弹上方显示数字,而是显示百分比。

那么需要将标识的生成器换一个构造函数。

new StandardCategoryItemLabelGenerator("{0} {1} {2} {3}", NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")); {0}表示甜点的种类,例如:“布丁”{1}表示地区,例如:七星区{2}表示数量,例如七星区的布丁数量是552{3}表示百分比,这样一来就在柱状图里面显示百分比//设定柱子上面的颜色customBarRenderer.setSeriesPaint(0,Color.decode("#24F4DB")); // 给series1 Bar customBarRenderer.setSeriesPaint(1,Color.decode("#7979FF")); // 给series2 Bar customBarRenderer.setSeriesPaint(2,Color.decode("#FF5555")); // 给series3 Bar customBarRenderer.setSeriesPaint(3,Color.decode("#F8D661")); // 给series4 Bar customBarRenderer.setSeriesPaint(4,Color.decode("#F284DC")); // 给series5 Bar customBarRenderer.setSeriesPaint(5,Color.decode("#00BF00")); // 给series6 Bar customBarRenderer.setSeriesOutlinePaint(0,Color.BLACK );//边框为黑色customBarRenderer.setSeriesOutlinePaint(1,Color.BLACK );//边框为黑色customBarRenderer.setSeriesOutlinePaint(2,Color.BLACK ); //边框为黑色customBarRenderer.setSeriesOutlinePaint(3,Color.BLACK );//边框为黑色customBarRenderer.setSeriesOutlinePaint(4,Color.BLACK );//边框为黑色customBarRenderer.setSeriesOutlinePaint(5,Color.BLACK ); //边框为黑色以下是来自网络的一些信息,对学习jfreechart很有用,虽然里面有些方法被抛弃了。

相关文档
最新文档