使用JFreeChart画柱状图

 /**
     * 画图
     *
     * @param histogramValueVoList
     * @return
     */
    private ImageEntity generatePicture(List<HistogramValueVo> histogramValueVoList, String pictureTitle, String xName, String yName, String dataName) {
        DefaultCategoryDataset dateSet = new DefaultCategoryDataset();
        for (HistogramValueVo histogramValueVo : histogramValueVoList) {
            dateSet.setValue(histogramValueVo.getValue(), dataName, histogramValueVo.getName());
        }
        /**
         * 标题,目录轴的显示标签,数值的显示标签,数据,图标方向  水平/垂直,是否显示图例,是否生成工具,是否生成URL链接
         */
        JFreeChart chart = ChartFactory.createBarChart(pictureTitle, xName, yName, dateSet, PlotOrientation.HORIZONTAL, true, true, false);
        //头部字体修改
        chart.getTitle().setFont(FontUtils.getFont("simsun.ttf", "新宋体", Font.BOLD, 20f));
        //VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭,使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,字体清晰度。
        chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        //图部分
        CategoryPlot categoryPlot = chart.getCategoryPlot();
        //背景颜色
        categoryPlot.setBackgroundPaint(new Color(241, 241, 245));
        //X轴
        CategoryAxis domainAxis = categoryPlot.getDomainAxis();
        //X轴下标  90°显示
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
        //自动换行    最多显示多少行
        domainAxis.setMaximumCategoryLabelLines(100);
        //下标
        domainAxis.setLabelFont(FontUtils.getFont("simsun.ttf", "黑体", Font.PLAIN, 14f));
        //X轴标题
        domainAxis.setTickLabelFont(FontUtils.getFont("simsun.ttf", "宋体", Font.PLAIN, 14f));
        //Y轴
        ValueAxis rangeAxis = categoryPlot.getRangeAxis();
        //下标
        rangeAxis.setLabelFont(FontUtils.getFont("simsun.ttf", "黑体", Font.PLAIN, 14f));
        //Y轴标题
        rangeAxis.setTickLabelFont(FontUtils.getFont("simsun.ttf", "宋体", Font.PLAIN, 14f));
        NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
        //取消自动设置Y轴刻度
        numberAxis.setAutoTickUnitSelection(false);
        //刻度大小
        numberAxis.setTickUnit(new NumberTickUnit(20));
        //和下面一行搭配使用   设置Y轴都是正数
        numberAxis.setAutoRangeStickyZero(true);
        numberAxis.setRangeType(RangeType.POSITIVE);
        //设置Y轴上的数值精度
        numberAxis.setNumberFormatOverride(new DecimalFormat("0"));
        //图标字体
        chart.getLegend().setItemFont(FontUtils.getFont("simsun.ttf", "黑体", Font.PLAIN, 14f));
        chart.getTitle().setFont(FontUtils.getFont("simsun.ttf", "黑体", Font.PLAIN, 14f));
        //图形修改
        BarRenderer renderer = (BarRenderer) categoryPlot.getRenderer();
        //设置柱状图上的数值精度
        renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("0.00")));
        //设置柱子之间的距离
        renderer.setItemMargin(0);
        renderer.setPositiveItemLabelPositionFallback(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER));
        renderer.setDefaultItemLabelFont(FontUtils.getFont("simsun.ttf", "黑体", Font.PLAIN, 14f));
        renderer.setDrawBarOutline(false);
        //设置柱子宽度
        renderer.setMaximumBarWidth(0.1);
        //设置柱子高度
        renderer.setMinimumBarLength(0.00);
        //设置最高柱子离顶部位置
        rangeAxis.setUpperMargin(0.18);
        //柱状体上的数值显示
        renderer.setDefaultItemLabelsVisible(true);
        //柱子颜色
        renderer.setSeriesPaint(0, new Color(0, 144, 230));
        String tempImgPath = this.getClass().getResource("/").getPath() + File.separator + "templates" + File.separator + getCharFileName();
        int height = 40 * histogramValueVoList.size();
        ImageEntity imageEntity = ChartUtils.creatImag(chart, tempImgPath, 500, height > 200 ? height : 200);
        return imageEntity;
    }
package com.utils;

import com.google.common.collect.Maps;

import java.awt.*;
import java.io.File;
import java.util.Map;

/**
 * @author leo.xiong
 * @version 2020/6/23
 * @className FontUtils
 * @Description
 */
public class FontUtils {
    private static Map<String, File> nameFileMap = Maps.newHashMap();

    private static synchronized void initFontFile(String fileName) {
        File file = nameFileMap.get(fileName);
        if (file == null) {
            String vPath = FontUtils.class.getResource("/").getPath() + File.separator + "bin" + File.separator + fileName;
            file = new java.io.File(vPath);
            nameFileMap.put(fileName, file);
        }
    }

    /**
     * LINUX中文乱码处理
     *
     * @param fileName
     * @param fontName
     * @param style
     * @param size
     * @return
     */
    public static Font getFont(String fileName, String fontName, int style, Float size) {
        Font defFont = new Font(fontName, style, 12);
        try {
            initFontFile(fileName);
            File file = nameFileMap.get(fileName);
            if (file == null || !file.exists()) {
                return defFont;
            }
            java.io.FileInputStream fi = new java.io.FileInputStream(file);
            Font nf = Font.createFont(Font.TRUETYPE_FONT, fi);
            fi.close();
            // 这一句需要注意
            // Font.deriveFont() 方法用来创建一个新的字体对象
            nf = nf.deriveFont(style, size);
            return nf;
        } catch (Exception e) {
        }
        return defFont;
    }
}
package com.utils;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.alibaba.dubbo.common.utils.Assert;
import com.alibaba.dubbo.common.utils.StringUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeriesCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author leo.xiong
 * @version 2020/6/18
 * @className ChartUtils
 * @Description
 */
public class ChartUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChartUtils.class);

    /**
     * 将图片转化为字节数组
     *
     * @return 字节数组
     */
    private static byte[] imgToByte(String tempImgPath) {
        File file = new File(tempImgPath);
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.getMessage();
        }
        //删除临时文件
        file.delete();
        return buffer;
    }

    public static JFreeChart xYLineChart(String title, String xAxisLabel, String yAxisLabel, XYSeriesCollection datas) {
        //创建主题样式
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");

        //设置标题字体
        standardChartTheme.setExtraLargeFont(FontUtils.getFont("simsun.ttf", "新宋体", Font.PLAIN, 18f));
//        //设置图例的字体
//        standardChartTheme.setRegularFont(FontUtils.getFont(path,"yqyzh.ttf","文泉驿正黑", Font.PLAIN, 12f));
//        //设置轴向的字体
//        standardChartTheme.setLargeFont(FontUtils.getFont(path,"yqyzh.ttf","文泉驿正黑", Font.PLAIN, 12f));
//        standardChartTheme.setSmallFont(FontUtils.getFont(path,"yqyzh.ttf","文泉驿正黑", Font.PLAIN, 10f));
        //设置图例的字体
        standardChartTheme.setRegularFont(FontUtils.getFont("simhei.ttf", "黑体", Font.PLAIN, 12f));
        //设置轴向的字体
        standardChartTheme.setLargeFont(FontUtils.getFont("simhei.ttf", "黑体", Font.PLAIN, 12f));
        standardChartTheme.setSmallFont(FontUtils.getFont("simhei.ttf", "黑体", Font.PLAIN, 10f));
        //设置主题样式
        ChartFactory.setChartTheme(standardChartTheme);
        //图标标题、数据集合、是否显示图例标识、是否显示tooltips、是否支持超链接
        JFreeChart chart = ChartFactory.createXYLineChart(title, xAxisLabel, yAxisLabel, (XYSeriesCollection) datas, PlotOrientation.VERTICAL, true, true, false);
        //将jfreechart里RenderingHints做文字渲染参数的修改
        chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(560, 367));
        final XYPlot plot = chart.getXYPlot();
//        setContentPane( chartPanel ); //原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/jfreechart/jfreechart_xy_chart.html
        ValueAxis domainAxis = plot.getDomainAxis();
        domainAxis.setTickLabelsVisible(true);//X轴的标题文字是否显示
        domainAxis.setTickMarksVisible(true);
        domainAxis.setAutoRange(true);
//        ValueAxis rAxisR = plot.getRangeAxis(1);
//        ((Axis) rAxisR).setTickLabelsVisible(true);//Y轴的标题文字是否显示
//        ((NumberAxis) rAxisR).setAutoRangeStickyZero(true);

        //设置抗锯齿
        chart.setTextAntiAlias(false);


//        plot.setNoDataMessage("no data");
        //设置背景图片颜色
        plot.setBackgroundImageAlpha(0.0f);
        //设置背景色
        plot.setBackgroundPaint(Color.WHITE);
        //设置网格横线颜色
        plot.setRangeGridlinePaint(Color.black);
        //忽略无值的分类
//        plot.setIgnoreNullValues(true);
//        plot.setBackgroundAlpha(0f);
//        //设置标签阴影颜色
//        plot.setShadowPaint(new Color(255,255,255));
//        //设置标签生成器(默认{0})
//        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}"));
        return chart;
    }

    public static JFreeChart addYLineChart(JFreeChart chart, XYSeriesCollection datas2, String twoyAxisLabel) {
        if (StringUtils.isEmpty(twoyAxisLabel)) {
            return chart;
        }
        NumberAxis axis2 = new NumberAxis(twoyAxisLabel);
//        axis2.setLabelFont(FontUtils.getFont(path,"yqyzh.ttf","文泉驿正黑", Font.PLAIN, 12f));
        axis2.setLabelFont(FontUtils.getFont("simhei.ttf", "黑体", Font.PLAIN, 12f));
        // -- 修改第2个Y轴的显示效果
        axis2.setAxisLinePaint(Color.BLUE);
        axis2.setLabelPaint(Color.BLUE);
        axis2.setTickLabelPaint(Color.BLUE);

        chart.getXYPlot().setRangeAxis(1, axis2);
        chart.getXYPlot().setDataset(1, datas2);
        chart.getXYPlot().mapDatasetToRangeAxis(1, 1);
        return chart;
    }

    public static ImageEntity creatImag(JFreeChart chart, String tempImgPath, int width, int height) {
        try {
            org.jfree.chart.ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, width, height);
        } catch (IOException e1) {
            LOGGER.warn("Failed to generate line chart!", e1);
        }
        ImageEntity imageEntity = new ImageEntity(imgToByte(tempImgPath), width, height);
        Assert.notNull(imageEntity.getData(), "Failed to generate line chart!");
        return imageEntity;
    }

}

猜你喜欢

转载自blog.csdn.net/xionglangs/article/details/115749962