如何去除XChart中绘图区域与坐标轴之间的内边距?
解决XYChart绘图区域与X/Y轴间内边距问题
要消除绘图区域和坐标轴之间的内边距,除了你已有的配置,还需要补充几个关键设置:
- 关闭坐标轴的自动范围扩展,手动将轴范围与数据的最小/最大值完全对齐
- 设置绘图区域边距为0
- 移除坐标轴偏移
修改后的完整代码如下:
// Create Chart XYChart chart = new XYChartBuilder().width(640).height(450).build(); // Customize Chart chart.getStyler().setPlotBorderVisible(false); chart.getStyler().setMarkerSize(0); chart.getStyler().setPlotGridLinesVisible(false); chart.getStyler().setAxisTicksVisible(false); chart.getStyler().setLegendVisible(false); chart.getStyler().setChartPadding(0); // 新增:设置绘图区域边距为0 chart.getStyler().setPlotMargin(0); // 新增:关闭坐标轴自动范围扩展 chart.getStyler().setXAxisMinAuto(false); chart.getStyler().setXAxisMaxAuto(false); chart.getStyler().setYAxisMinAuto(false); chart.getStyler().setYAxisMaxAuto(false); // 新增:移除坐标轴偏移 chart.getStyler().setAxisOffset(0); chart.getStyler().setDefaultSeriesRenderStyle(XYSeries.XYSeriesRenderStyle.Area); // Series double[] x1 = {0, 3, 5}; double[] y1 = {-3, 5, 9}; double[] x2 = {5, 7, 9}; double[] y2 = {9, 6, 5}; chart.addSeries("a", x1, y1); chart.addSeries("b", x2, y2); // 手动设置X轴范围为数据的最小/最大值 double minX = Math.min(Arrays.stream(x1).min().orElse(0), Arrays.stream(x2).min().orElse(0)); double maxX = Math.max(Arrays.stream(x1).max().orElse(0), Arrays.stream(x2).max().orElse(0)); chart.getStyler().setXAxisMin(minX); chart.getStyler().setXAxisMax(maxX); // 手动设置Y轴范围为数据的最小/最大值 double minY = Math.min(Arrays.stream(y1).min().orElse(0), Arrays.stream(y2).min().orElse(0)); double maxY = Math.max(Arrays.stream(y1).max().orElse(0), Arrays.stream(y2).max().orElse(0)); chart.getStyler().setYAxisMin(minY); chart.getStyler().setYAxisMax(maxY); try { BitmapEncoder.saveBitmap(chart, "./report-template/chart/Sample_Chart.png", BitmapEncoder.BitmapFormat.PNG); } catch (IOException e) { throw new RuntimeException("Failed to save the chart!!! " + e); }
关键配置说明
setPlotMargin(0):直接消除绘图区域自身的边距- 关闭
X/YAxisMinAuto和MaxAuto:避免库自动给轴范围添加额外留白 - 手动设置轴范围为数据极值:确保图表内容完全贴合坐标轴
setAxisOffset(0):移除坐标轴与绘图区域之间的偏移量
内容的提问来源于stack exchange,提问作者constantlyFlagged
相关产品推荐
相关产品推荐

