Apache POI折线图标题格式问题:标题重叠数据、字体调整
解决Apache POI折线图标题重叠与字体调整问题
嘿,我来帮你搞定这个图表标题的问题!针对你遇到的标题和数据重叠、需要调整位置及字体的需求,我整理了具体的代码修改方案:
1. 把标题移到图表上方,避免重叠
默认情况下,POI创建的图表标题是嵌在绘图区域里的,所以才会和数据撞在一起。我们只需要两步就能把它移到顶部独立区域:
首先关闭标题的覆盖模式,然后调整绘图区的上边距,给标题留出空间:
// 原标题设置后添加这几行 chart.setTitleOverlay(false); // 关键:让标题独立于绘图区域,不再覆盖数据 // 调整绘图区的内边距,上边留出15%的空间给标题(可根据需求调整比例) ChartPlot plot = chart.getPlot(); if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; xyPlot.setInsets(new RectangleInsets(0.15, 0.05, 0.05, 0.05)); }
setTitleOverlay(false)是核心,它会把标题从绘图区里“拉”出来,放到图表顶部的专属位置。然后通过setInsets调整绘图区的上边距,确保标题和你的8000数值上方有足够空隙。
2. 缩小标题的字号(还能调整其他字体样式)
要修改标题字体,我们需要获取标题的文本对象,然后自定义字体属性:
// 获取标题对象并设置字体 ChartTitle title = chart.getTitle(); RichTextString titleText = title.getText(); // 创建新字体,设置字号为10(你可以改成自己想要的大小) Font font = sheet.getWorkbook().createFont(); font.setFontHeightInPoints((short)10); font.setFontName("Arial"); // 可选:指定字体名称 // 把字体应用到整个标题 titleText.applyFont(font); title.setText(titleText);
如果需要额外样式,比如加粗、改颜色,直接在Font对象上设置就行:
font.setBold(true); // 加粗 font.setColor(IndexedColors.DARK_BLUE.getIndex()); // 深蓝色字体
修改后的完整代码
把这些修改整合到你的原有代码里,最终版本如下:
Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); Chart chart = drawing.createChart(anchor); // 设置标题并调整位置 chart.setTitleText("This is my title"); chart.setTitleOverlay(false); // 调整绘图区边距 ChartPlot plot = chart.getPlot(); if (plot instanceof XYPlot) { XYPlot xyPlot = (XYPlot) plot; xyPlot.setInsets(new RectangleInsets(0.15, 0.05, 0.05, 0.05)); } // 调整标题字体 ChartTitle title = chart.getTitle(); RichTextString titleText = title.getText(); Font font = sheet.getWorkbook().createFont(); font.setFontHeightInPoints((short)10); font.setFontName("Arial"); titleText.applyFont(font); title.setText(titleText); // 原有坐标轴和数据逻辑 ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); ChartDataSource<Integer> test = DataSources.fromArray(new Integer[]{2011,2012,2013,2014,2015,2016,2017}); ChartDataSource<Integer> test2 = DataSources.fromArray(new Integer[]{4805, 7351, 5333, 7183, 6230, 4050, 6963}); LineChartData data = chart.getChartDataFactory().createLineChartData(); data.addSeries(test, test2); chart.plot(data, bottomAxis, leftAxis);
小提示
- 如果你用的是
.xlsx格式(XSSFWorkbook),可以用XSSFFont来设置更多高级样式,比如字体阴影、斜体等。 RectangleInsets的四个参数是上、右、下、左的边距比例(0-1之间),如果觉得标题空间不够,把第一个参数调大一点就行,比如改成0.2。
内容的提问来源于stack exchange,提问作者Raymond Holguin
相关产品推荐
相关产品推荐

