使用JFreeChart画柱状图
2021/4/16 10:56:42
本文主要是介绍使用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)); //图部分 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; } }
这篇关于使用JFreeChart画柱状图的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-25【机器学习(二)】分类和回归任务-决策树(Decision Tree,DT)算法-Sentosa_DSML社区版
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享