在当今数据时代,实时数据可视化已成为企业和个人决策的关键环节之一。作为一名 Java 开发者,掌握实时数据可视化库的使用,可以帮助您更好地展示数据,提高工作效率和决策质量。本文将为您介绍目前市面上流行的八个 Java 实时数据可视化库,旨在帮助您快速入门和提高数据可视化能力。
【Java万花筒】数据之翼:Java库助您飞跃科学计算高峰
【Java万花筒】Java图形库探秘:创意编程、数据可视化与用户界面设计
【Java万花筒】数据可视化利器:Java图表和图形库全面对比
【Java万花筒】数据魔术师:探索Java商业智能与数据可视化
欢迎订阅专栏:Java万花筒
Grafana 是一款开源的度量分析和可视化工具,支持多种数据源,如 Graphite、InfluxDB、Prometheus 等。Grafana 可以帮助用户创建、探索和分享各种各样的可视化面板。
Grafana Java Client 是一个用于操作 Grafana 的 Java 库,它提供了一系列的 API 来管理 Grafana 的 Dashboard、数据源、组织、用户等资源。
<dependency>
<groupId>com.github.hipagesgroupId>
<artifactId>grafana-clientartifactId>
<version>0.3.2version>
dependency>
import com.github.hipages.grafana.client.GrafanaClient;
import com.github.hipages.grafana.client.GrafanaClientBuilder;
GrafanaClient client = new GrafanaClientBuilder()
.url("http://localhost:3000")
.auth("admin", "admin")
.build();
import com.github.hipages.grafana.client.model.Dashboard;
import com.github.hipages.grafana.client.model.Row;
import com.github.hipages.grafana.client.model.Text;
import com.github.hipages.grafana.client.model.TimeSeries;
Dashboard dashboard = new Dashboard();
dashboard.setTitle("My Dashboard");
Row row = new Row();
row.setTitle("Row 1");
Text text = new Text();
text.setContent("Hello, Grafana!");
TimeSeries timeSeries = new TimeSeries();
timeSeries.setAlias("Series A");
timeSeries.setTarget("metric1");
row.addPanel(text);
row.addPanel(timeSeries);
dashboard.addRow(row);
client.dashboards().create(dashboard);
import com.github.hipages.grafana.client.model.DataSource;
import com.github.hipages.grafana.client.model.GraphiteDataSource;
DataSource dataSource = new GraphiteDataSource();
dataSource.setName("Graphite");
dataSource.setUrl("http://graphite:8080");
client.dataSources().create(dataSource);
import com.github.hipages.grafana.client.model.GraphPanel;
import com.github.hipages.grafana.client.model.Target;
GraphPanel graphPanel = new GraphPanel();
graphPanel.setTitle("Graph Panel");
Target target = new Target();
target.setTarget("metric1");
target.setRefId("A");
graphPanel.addTarget(target);
dashboard.getFirstRow().addPanel(graphPanel);
client.dashboards().update(dashboard);
import com.github.hipages.grafana.client.model.TemplateVariable;
import com.github.hipages.grafana.client.model.Query;
import com.github.hipages.grafana.client.model.Datasource;
TemplateVariable templateVariable = new TemplateVariable();
templateVariable.setName("host");
templateVariable.setType("query");
templateVariable.setQuery(new Query("host"));
templateVariable.setDatasource(new Datasource("Graphite"));
dashboard.addTemplateVariable(templateVariable);
client.dashboards().update(dashboard);
import com.github.hipages.grafana.client.model.Alert;
import com.github.hipages.grafana.client.model.Condition;
import com.github.hipages.grafana.client.model.Notification;
Alert alert = new Alert();
alert.setName("Metric 1 Alert");
alert.setRuleId(graphPanel.getId());
alert.setMessage("Metric 1 is too high");
Condition condition = new Condition();
condition.setEvalMatches(false);
condition.setOperator("gt");
condition.setQuery("$A");
condition.setThreshold(100);
alert.setConditions(Arrays.asList(condition));
Notification notification = new Notification();
notification.setType("email");
notification.setSettings(Map.of("addresses", Arrays.asList("[email protected]")));
alert.setNotifications(Arrays.asList(notification));
client.alerts().create(alert);
import com.github.hipages.grafana.client.model.Role;
import com.github.hipages.grafana.client.model.Permission;
Role role = new Role();
role.setName("Viewer");
role.setPermissions(Arrays.asList(Permission.DASHBOARDS_READ));
client.roles().create(role);
client.dashboards().updatePermissions(dashboard.getId(), Map.of("Viewer", Permission.DASHBOARDS_READ));
ECharts 是一个由百度开发的开源可视化库,基于 HTML5 Canvas 实现,支持多种图表类型,如折线图、柱状图、饼图等。
ECharts Java 是一个用于操作 ECharts 的 Java 库,它提供了一系列的 API 来创建和配置各种 ECharts 图表。
<dependency>
<groupId>com.github.abel533groupId>
<artifactId>echartsartifactId>
<version>4.7.0version>
dependency>
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Pie;
Option option = new Option();
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.series.Bar;
CategoryAxis xAxis = new CategoryAxis();
xAxis.data("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
ValueAxis yAxis = new ValueAxis();
yAxis.setType(AxisType.value);
Bar bar = new Bar();
bar.data(150, 230, 224, 218, 135, 147, 260);
option.setxAxis(xAxis);
option.setyAxis(yAxis);
option.setSeries(bar);
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.series.Line;
CategoryAxis xAxis = new CategoryAxis();
xAxis.data("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
ValueAxis yAxis = new ValueAxis();
yAxis.setType(AxisType.value);
Line line = new Line();
line.data(820, 932, 901, 934, 1290, 1330, 1320);
option.setxAxis(xAxis);
option.setyAxis(yAxis);
option.setSeries(line);
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.feature.SaveAsImage;
option.setTitle("ECharts Example");
option.setTooltipTrigger(Trigger.axis);
option.setLegendData("Email", "Union Ads", "Video Ads", "Direct", "Search Engine");
option.setToolboxFeature(new MagicType(Tool.line, Tool.bar), new SaveAsImage());
import com.github.abel533.echarts.series.Custom;
Custom custom = new Custom();
custom.setRenderItem("myRenderItem");
custom.setData(10, 20, 30, 40, 50);
option.setSeries(custom);
import com.github.abel533.echarts.series.EffectScatter;
import com.github.abel533.echarts.series.Scatter;
Scatter scatter = new Scatter();
scatter.setSymbolSize(10);
scatter.setData(10, 20, 30, 40, 50);
EffectScatter effectScatter = new EffectScatter();
effectScatter.setSymbolSize(10);
effectScatter.setData(10, 20, 30, 40, 50);
option.setSeries(scatter, effectScatter);
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.series.Line;
CategoryAxis xAxis = new CategoryAxis();
xAxis.data("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
ValueAxis yAxis = new ValueAxis();
yAxis.setType(AxisType.value);
Line line1 = new Line();
line1.data(820, 932, 901, 934, 1290, 1330, 1320);
Line line2 = new Line();
line2.data(10, 20, 30, 40, 50, 60, 70);
option.setxAxis(xAxis);
option.setyAxis(yAxis);
option.setSeries(line1, line2);
option.setTooltipAxisPointerType("cross");
option.setTooltipTrigger(Trigger.axis);
XChart 是一个用于创建各种图表的 Java 库,支持柱状图、折线图、饼图等多种图表类型。
XChart 提供了一系列的 API 来创建和配置各种图表,支持自定义图表样式。
<dependency>
<groupId>com.github.knowmgroupId>
<artifactId>xchartartifactId>
<version>3.8.2version>
dependency>
import org.knowm.xchart.*;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.markers.SeriesMarkers;
// 设置图表主题
ChartTheme theme = ChartTheme.Matlab;
XYChart chart = QuickChart.getChart("Sample Chart", "X", "Y", "y = x^2", new double[]{-10, -5, 0, 5, 10}, new double[]{100, 25, 0, 25, 100});
chart.getStyler().setChartTheme(theme);
// 设置图例位置
chart.getStyler().setLegendPosition(LegendPosition.InsideNE);
// 设置标题和子标题
chart.setTitle("XChart Example");
chart.setSubTitle("Subtitle");
// 设置轴标签
chart.getXAxis().setTitle("X Axis");
chart.getYAxis().setTitle("Y Axis");
// 设置网格线
chart.getStyler().setYAxisMinorGridlinesVisible(false);
chart.getStyler().setXAxisMinorGridlinesVisible(false);
// 设置数据点标记
chart.getSeriesMap().get("y = x^2").setMarker(SeriesMarkers.CIRCLE);
// 显示图表
new SwingWrapper<>(chart).displayChart();
注意:在使用 XChart 之前,请确保已经正确安装了 JavaFX。如果您使用的是 IntelliJ IDEA,可以按照以下步骤进行安装:
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.CategoryChartBuilder;
CategoryChart chart = new CategoryChartBuilder()
.title("Sample Chart")
.xAxisTitle("Category")
.yAxisTitle("Value")
.build();
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.Series;
CategoryChart chart = ... // 创建图表
Series series = chart.addSeries("Series A", 10, 20, 30, 40, 50);
series.setMarkerColor(ChartColor.RED);
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.style.Styler.ChartTheme;
CategoryChart chart = ... // 创建图表
chart.getStyler().setChartTheme(ChartTheme.GGPlot2);
chart.getStyler().setLegendVisible(false);
chart.getStyler().setMarkerSize(10);
new SwingWrapper(chart).displayChart();
import org.knowm.xchart.XYChart;
import org.knowm.xchart.XYChartBuilder;
import org.knowm.xchart.XYSeries.XYSeriesRenderStyle;
XYChart chart = new XYChartBuilder()
.title("Custom Chart")
.xAxisTitle("X Axis")
.yAxisTitle("Y Axis")
.build();
chart.addSeries("Series A", new double[] {1, 2, 3, 4, 5}, new double[] {10, 20, 30, 40, 50})
.setRenderStyle(XYSeriesRenderStyle.Line);
new SwingWrapper(chart).displayChart();
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.animation.ChartAnimator;
CategoryChart chart = ... // 创建图表
new SwingWrapper(chart).displayChart();
ChartAnimator animator = new ChartAnimator(chart);
animator.animate(1000); // 持续 1 秒
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.BitmapEncoder;
CategoryChart chart = ... // 创建图表
BitmapEncoder.saveBitmap(chart, "./chart.png");
JavaFX 是一个用于创建桌面应用程序和富互联网应用程序的 Java 库,支持各种图形、媒体和控件。
JavaFX 提供了一系列的 API 来创建和配置各种控件和图形,支持自定义样式和动画。
<dependency>
<groupId>org.openjfxgroupId>
<artifactId>javafx-controlsartifactId>
<version>16version>
dependency>
<dependency>
<groupId>org.openjfxgroupId>
<artifactId>javafx-fxmlartifactId>
<version>16version>
dependency>
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("JavaFX Sample");
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
<AnchorPane xmlns="http://javafx.com/javafx/16"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.example.Controller">
<LineChart fx:id="lineChart" title="JavaFX Chart" animated="false" createSymbols="false">
<xAxis>
<NumberAxis label="X Axis" autoRanging="false" lowerBound="0" upperBound="10" tickUnit="1"/>
xAxis>
<yAxis>
<NumberAxis label="Y Axis" autoRanging="false" lowerBound="0" upperBound="100" tickUnit="10"/>
yAxis>
LineChart>
AnchorPane>
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import java.util.Random;
public class Controller {
@FXML
private LineChart<Number, Number> lineChart;
public void initialize() {
NumberAxis xAxis = (NumberAxis) lineChart.getXAxis();
NumberAxis yAxis = (NumberAxis) lineChart.getYAxis();
XYChart.Series<Number, Number> series = new XYChart.Series<>();
series.setName("Series A");
Random random = new Random();
for (int i = 0; i < 10; i++) {
series.getData().add(new XYChart.Data<>(i, random.nextInt(100)));
}
lineChart.getData().add(series);
}
}
Vaadin 是一个用于创建 Web 应用程序的 Java 框架,支持各种控件和组件。
Vaadin 提供了一系列的 API 来创建和配置各种控件和组件,支持自定义样式和事件处理。
<dependency>
<groupId>com.vaadingroupId>
<artifactId>vaadin-chartsartifactId>
<version>4.4.7version>
dependency>
import com.vaadin.flow.component.page.AppShellConfigurator;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.theme.Theme;
@Theme("my-theme")
@PWA(name = "My App", shortName = "My App")
public class AppShellConfigurator implements AppShellConfigurator {
@Override
public void onInit(AppShellSettings settings) {
}
}
import com.vaadin.flow.component.charts.Chart;
import com.vaadin.flow.component.charts.model.ChartType;
import com.vaadin.flow.component.charts.model.Configuration;
import com.vaadin.flow.component.charts.model.Title;
import com.vaadin.flow.component.charts.model.Tooltip;
import com.vaadin.flow.component.charts.model.style.SolidColor;
import com.vaadin.flow.router.Route;
import java.util.Random;
@Route("chart")
public class ChartView extends Div {
public ChartView() {
Configuration configuration = getConfiguration();
Chart chart = new Chart(configuration);
add(chart);
}
private Configuration getConfiguration() {
Configuration configuration = new Configuration();
configuration.setChartType(ChartType.LINE);
configuration.setTitle(new Title("Vaadin Chart"));
configuration.getTooltip().setValueSuffix(" units");
configuration.getxAxis().setTitle("X Axis");
configuration.getyAxis().setTitle("Y Axis");
Random random = new Random();
for (int i = 0; i < 10; i++) {
configuration.addSeries("Series A", new double[] {i}, new double[] {random.nextInt(100)});
}
return configuration;
}
}
Birt 是一个用于创建报表的开源 Java 库,支持各种图表、表格和跨表。
Birt 提供了一系列的 API 来创建和配置各种报表,支持自定义样式和数据源。
<dependency>
<groupId>org.eclipse.birt.runtimegroupId>
<artifactId>org.eclipse.birt.runtimeartifactId>
<version>4.8.0version>
dependency>
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
public class BirtReport {
public void generateReport() {
EngineConfig config = new EngineConfig();
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
IReportEngine engine = factory.createReportEngine(config);
IReportRunnable design = engine.openReportDesign("report.rptdesign");
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
task.setRenderOption(new RenderOption());
task.setAppContext(new AppContext());
task.run();
task.close();
engine.destroy();
Platform.shutdown();
}
}
JFreeChart 是一个用于创建各种图表的 Java 库,支持柱状图、折线图、饼图等多种图表类型。
JFreeChart 提供了一系列的 API 来创建和配置各种图表,支持自定义图表样式。
<dependency>
<groupId>org.jfreegroupId>
<artifactId>jfreechartartifactId>
<version>1.5.3version>
dependency>
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import java.awt.EventQueue;
public class JFreeChartExample extends ApplicationFrame {
public JFreeChartExample(String title) {
super(title);
setContentPane(createChartPanel());
}
private ChartPanel createChartPanel() {
JFreeChart chart = ChartFactory.createLineChart(
"JFreeChart Example",
"X Axis",
"Y Axis",
createDataset(),
PlotOrientation.VERTICAL,
true, true, false);
return new ChartPanel(chart);
}
private DefaultCategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(10.0, "Series A", "Category 1");
dataset.addValue(20.0, "Series A", "Category 2");
dataset.addValue(30.0, "Series A", "Category 3");
dataset.addValue(40.0, "Series A", "Category 4");
dataset.addValue(50.0, "Series A", "Category 5");
return dataset;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFreeChartExample example = new JFreeChartExample("JFreeChart Example");
example.setVisible(true);
});
}
}
JasperReports 是一个用于创建报表的 Java 库,支持各种图表、表格和跨表。
JasperReports 提供了一系列的 API 来创建和配置各种报表,支持自定义样式和数据源。
<dependency>
<groupId>net.sf.jasperreportsgroupId>
<artifactId>jasperreportsartifactId>
<version>6.17.0version>
dependency>
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JasperReportExample {
public void generateReport() throws Exception {
String jrxmlFile = "report.jrxml";
JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlFile);
List<ReportBean> reportBeans = new ArrayList<>();
reportBeans.add(new ReportBean("Category 1", 10.0));
reportBeans.add(new ReportBean("Category 2", 20.0));
reportBeans.add(new ReportBean("Category 3", 30.0));
reportBeans.add(new ReportBean("Category 4", 40.0));
reportBeans.add(new ReportBean("Category 5", 50.0));
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(reportBeans);
Map<String, Object> parameters = new HashMap<>();
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, new File("report.pdf").getAbsolutePath());
}
public static class ReportBean {
private String category;
private double value;
public ReportBean(String category, double value) {
this.category = category;
this.value = value;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
}
本文从多个方面对比了八个Java实时数据可视化库,从特点、安装和配置、基本使用、高级用法等方面进行了详细介绍。这些库各有优缺点和适用场景,选择最适合自己的工具需要结合实际情况综合考虑。通过本文的学习,您可以更好地理解这些库,提高数据可视化能力,更好地应对工作中的需求。