Java的柱状图统计如何实现
时间: 2024-01-21 13:18:02 浏览: 87
java实现柱状图
4星 · 用户满意度95%
Java实现柱状图统计需要使用Java图形库,例如JFreeChart。以下是一个简单的示例代码:
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChartExample extends JFrame {
private static final long serialVersionUID = 1L;
public BarChartExample() {
super("Bar Chart Example");
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
Random random = new Random();
for (int i = 1; i <= 10; i++) {
dataset.addValue(random.nextInt(100), "Series 1", "Category " + i);
}
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 300));
setContentPane(chartPanel);
}
private JFreeChart createChart(DefaultCategoryDataset dataset) {
JFreeChart chart = ChartFactory.createBarChart(
"Bar Chart Demo", // chart title
"Category", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips?
false // URLs?
);
// set the background color for the chart
chart.setBackgroundPaint(Color.white);
// get a reference to the plot for further customization
CategoryPlot plot = chart.getCategoryPlot();
// set the range axis to display integers only
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// disable bar outlines
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
// set up gradient paints for series
Paint[] colors = new Paint[] {
new GradientPaint(0, 0, new Color(79, 129, 189), 0, 0, new Color(41, 67, 97)),
new GradientPaint(0, 0, new Color(192, 80, 77), 0, 0, new Color(123, 52, 51)),
new GradientPaint(0, 0, new Color(155, 187, 89), 0, 0, new Color(84, 102, 45))
};
for (int i = 0; i < dataset.getRowCount(); i++) {
renderer.setSeriesPaint(i, colors[i % colors.length]);
}
// customize the category axis labels
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setTickLabelFont(domainAxis.getTickLabelFont().deriveFont(14.0f));
domainAxis.setCategoryMargin(0.25);
domainAxis.setUpperMargin(0.02);
return chart;
}
public static void main(String[] args) {
BarChartExample demo = new BarChartExample();
demo.pack();
demo.setLocationRelativeTo(null);
demo.setVisible(true);
}
}
```
该示例代码使用了JFreeChart库创建了一个简单的柱状图,数据来源于一个随机数生成器。你可以根据自己的需要修改数据和绘图属性。
阅读全文