java - JFreeChart | 如何在每个条形图的顶部添加百分比并格式化域轴(X 轴)刻度标签?
问题描述
我正在使用JFreeChart,以下是我开发的图表的屏幕截图和相关代码。
private void getBarChart(List<Data> data) {
JFreeChart barChart = ChartFactory.createBarChart("", "", "", createDataset(data), PlotOrientation.VERTICAL, false, true, false);
CategoryPlot plot = barChart.getCategoryPlot();
plot.getRenderer().setSeriesPaint(0, new Color(7, 43, 97));
barChart.getCategoryPlot().getRangeAxis().setLowerBound(0);
barChart.getCategoryPlot().getRangeAxis().setUpperBound(1);
NumberAxis xAxis2 = (NumberAxis) barChart.getCategoryPlot().getRangeAxis();
xAxis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
plot.getRenderer().setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator());
plot.getRenderer().setSeriesItemLabelsVisible(1, true);
plot.getRenderer().setBaseItemLabelsVisible(true);
plot.getRenderer().setBaseSeriesVisible(true);
barChart.getCategoryPlot().setRenderer(plot.getRenderer());
BarRenderer.setDefaultBarPainter(new StandardBarPainter());
((BarRenderer) plot.getRenderer()).setBarPainter(new StandardBarPainter());
BufferedImage image = new BufferedImage(650, 250, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
Rectangle r = new Rectangle(0, 0, 650, 250);
barChart.draw(g2, r);
BufferedImage chartImage = barChart.createBufferedImage(600, 400, null);
}
问题 1.) 如何按照预期的图表格式化 x 轴标签?(barChart.getCategoryPlot().getDomainAxis() 中的 CategoryLables 或 TickLabels)
问题 2.)每个条形 (SeriesItemLabels) 顶部显示的值需要使用类似于 y 轴的百分比标记 (%) 进行格式化。(我也认为,就像我在 xAxis2.setNumberFormatOverride 中所做的那样,这些值将自动乘以 100%。现在它只显示十进制值)。如何做到这一点?
请帮帮我。谢谢。
解决方案
从 开始BarChartDemo1.java
,为JFreechart 1.5更新,下面说明了以下替代方案。
如here和here所示,您可以
setCategoryLabelPositions()
在域轴上调用并使用它CategoryLabelPositions.createUpRotationLabelPositions
来微调角度。下面的示例逆时针旋转 π/4 弧度或 45°。CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions( CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0));
此处显示的,您可以构造自定义
StandardCategoryItemLabelGenerator
,但您可能希望使用ArgumentIndex{3}
,它是作为列总数百分比的值,以及合适的NumberFormat
.renderer.setDefaultItemLabelGenerator( new StandardCategoryItemLabelGenerator( "{3}", NumberFormat.getPercentInstance())); renderer.setDefaultItemLabelsVisible(true);
推荐阅读
- php - 使用 in_array() 比较字符串失败
- android - 如何使用 kotlin 将 imageview 保存到 sharedpreference?
- javascript - 使用jQuery动画填充进度条?
- android - 如何在Android的BottomNavigationView中隐藏一个按钮
- javascript - 如何根据值将整数转换为特定字符串
- pandas - 识别 PySpark DF ArrayType 列上运行的干净方法
- python - 如何在 MacOS Catalina 上以管理员身份运行 Anaconda?
- jupyter-notebook - 在使用 jupyter notebook 时,我得到了 CERTIFICATE_VERIFY_FAILED
- reactjs - 问题回复:customHooks、setTimeout 闭包和 useSelector
- python - 使用 openpyxl 使用计数器循环遍历 excel 文件中的列