jfreechart柱状图示例

来源:互联网 发布:中国电信网络传真系统 编辑:程序博客网 时间:2024/05/17 03:01
public static void main(String[] args){    //创建主题样式 ,以下代码用于解决中文乱码问题    StandardChartTheme standardChartTheme=new StandardChartTheme("CN");    //设置标题字体    standardChartTheme.setExtraLargeFont(new Font("宋体",Font.BOLD,20));    //设置图例的字体    standardChartTheme.setRegularFont(new Font("宋体",Font.PLAIN,15));    //设置轴向的字体    standardChartTheme.setLargeFont(new Font("宋体",Font.PLAIN,15));    //应用主题样式    ChartFactory.setChartTheme(standardChartTheme);    //数据源    DefaultCategoryDataset dataset = new DefaultCategoryDataset();    dataset.addValue(510, "22", "苹果");    dataset.addValue(320, "45", "香蕉");    dataset.addValue(580, "31", "橘子");    dataset.addValue(390, "12", "梨子");     //创建图    JFreeChart chart = ChartFactory.createBarChart3D("数量统计图",        null,        null,        dataset,        PlotOrientation.VERTICAL,        false,        false,        false);    CategoryPlot plot=(CategoryPlot)chart.getPlot();    //x轴    CategoryAxis categoryAxis=plot.getDomainAxis();    //分类标签以45度倾斜    categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);    //设置画布颜色为白色    plot.setBackgroundPaint(SystemColor.WHITE);        //设置水平方向背景线颜色    plot.setRangeGridlinePaint(Color.gray);    //设置是否显示水平方向背景线,默认值为true    plot.setRangeGridlinesVisible(true);    //设置垂直方向背景线颜色    plot.setDomainGridlinePaint(Color.gray);    //设置是否显示垂直方向背景线,默认值为true    plot.setDomainGridlinesVisible(true);    // 设置柱的透明度    plot.setForegroundAlpha(0.7f);    ValueAxis rangeAxis = plot.getRangeAxis();    //设置最高的一个柱与图片顶端的距离,以保证柱子上方的数值能展示出来    rangeAxis.setUpperMargin(0.15);    BarRenderer3D barRender=(BarRenderer3D)plot.getRenderer();    //设置柱子的最大宽度    barRender.setMaximumBarWidth(0.04);    //设置柱子直接的间距    barRender.setItemMargin(0.000000005);    //显示每个柱的数值    barRender.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());    barRender.setBaseItemLabelsVisible(true);    //设置柱子数值label显示位置    barRender.setBasePositiveItemLabelPosition(new ItemLabelPosition(    ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));    // 设置柱形图上的文字偏离值    barRender.setItemLabelAnchorOffset(10D);    //最短的BAR长度,避免数值太小而显示不出    barRender.setMinimumBarLength(0.5);    //设置柱子的随机颜色    for (int k = 0; k < barRender.getColumnCount(); k++)    {    barRender.setSeriesPaint(k, getRandomColor());        //设置边框为黑色     barRender.setSeriesOutlinePaint(k,Color.BLACK);    }        ChartFrame chartFrame=new ChartFrame("数量统计图",chart);    //以合适的大小展现图形    chartFrame.pack();    //图形是否可见    chartFrame.setVisible(true);}private static Color getRandomColor(){    Color color = new Color(         (new Double(Math.random() * 128)).intValue() + 128,         (new Double(Math.random() * 128)).intValue() + 128,         (new Double(Math.random() * 128)).intValue() + 128);    return color;}

效果图如下:


0 0