Socket & Highchart Gauge: Real-Time Data Visualization
Ashutosh Sharma
Posted on June 7, 2023
Real-time data visualization is an effective technique for monitoring, analyzing, and making decisions based on real-time data updates. We can create interactive and dynamic visualizations that provide real-time insights by combining WebSocket for real-time data communication and Highchart's gauge chart for visual representation. In this article, we will look at real-time data visualization use cases and show how to implement them using socket communication and Highchart's gauge chart.
Use Cases of Real-Time Data Visualization
Real-time data visualization with WebSocket and Highchart's gauge chart finds applications in various domains. Let's explore a few notable use cases:
IoT Sensor Monitoring: Sensors collect data from various devices and environments in IoT (Internet of Things) applications. Users can monitor sensor readings such as temperature, humidity, or air quality in real time using real-time data visualization. Users can quickly identify anomalies or trends by visualizing this data on gauge charts, allowing them to make informed decisions and take appropriate actions.
Financial Data Analysis: In financial systems where real-time market data, stock prices, or currency exchange rates are constantly changing, real-time visualization is critical. Traders and investors can quickly assess market conditions, identify patterns, and make informed decisions about investments or trading strategies by visualizing financial data on gauge charts.
Network Monitoring and Performance Analysis: Real-time data visualization can help network administrators and IT teams monitor network performance metrics like bandwidth usage, latency, and packet loss. Gauge charts can provide an intuitive representation of these metrics, allowing administrators to quickly identify anomalies or bottlenecks and take proactive measures to ensure network stability and performance.
Healthcare Monitoring: Real-time data visualization is essential in healthcare applications, particularly in monitoring patients' vital signs. Healthcare professionals can track metrics such as heart rate, blood pressure, and oxygen saturation in real-time by integrating sensors with real-time gauge charts. This allows healthcare providers to respond quickly and provide timely interventions by detecting abnormal readings early.
Environmental Monitoring: In environmental monitoring systems such as weather stations or pollution monitoring, real-time visualization is critical. Temperature, humidity, air quality index, and pollutant levels can all be displayed in real time on gauge charts. This enables researchers, environmentalists, and policymakers to monitor and analyze environmental conditions in real time, allowing them to make informed decisions.
These are just a few examples of how real-time data visualization with WebSocket and Highchart's gauge chart can be applied across different domains. The versatility and flexibility of this approach make it a powerful tool for real-time monitoring, analysis, and decision-making. Now, let's dive into the technical aspects of setting up the server and creating the HTML page to implement real-time gauge chart visualization.
Technical Implementation
We will create a sample application for monitoring temperature using a WebSocket server and a gauge chart to demonstrate real-time data visualization. The server will simulate temperature data, and the gauge chart will display the current temperature.
Setting up the Server
To begin, let's set up a server that establishes a WebSocket connection and sends data to connected clients. We'll be using Node.js and the ws
library to create a simple WebSocket server.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 1234 });
console.log('WebSocket server started');
wss.on('connection', (ws) => {
console.log('New WebSocket connection');
const interval = setInterval(() => {
const data = String(Math.floor(Math.random() * 100) + 1);
ws.send(data);
console.log('Sent data:', data);
}, 2000);
ws.on('close', () => {
console.log('WebSocket connection closed');
clearInterval(interval);
});
});
In the code above, we create a WebSocket server that listens on port 1234. When a client connects, a new WebSocket connection event is triggered. We start sending random data to the client every 2 seconds using a setInterval
function. If the client disconnects, we clear the interval to stop sending data.
Creating the HTML Page
Next, let's create an HTML page that will host our Highcharts gauge chart and handle the WebSocket connection to receive real-time data updates. We'll be using Highcharts version 9.3.1.
<!DOCTYPE html>
<html>
<head>
<title>Gauge Chart Example</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/solid-gauge.js"></script>
</head>
<body>
<div id="chart-container" style="width: 400px; height: 300px;"></div>
<script>
var container = document.createElement('div');
document.body.appendChild(container);
window.chart = new Highcharts.Chart({
chart: {
renderTo: container,
type: 'gauge'
},
title: {
text: 'Humidity'
},
series: [{
name: 'Humidity',
data: [0],
dataLabels: {
format: '{y} %'
},
yAxis: {
min: 0,
max: 100
},
tooltip: {
valueSuffix: ' %'
}
}]
});
var socket = new WebSocket('ws://localhost:1234');
socket.onopen = function (event) {
console.log('WebSocket connection established.');
};
socket.onmessage = function (event) {
var value = parseInt(event.data);
console.log('Received data:', value);
chart.series[0].points[0].update(value);
};
</script>
</body>
</html>
In the HTML code, we include the Highcharts library from the Highcharts CDN. The <div>
element with the id chart-container is where the gauge chart will be rendered.
Inside the <script>
tag, we create a new Highcharts chart by instantiating the Highcharts.Chart constructor. We configure the chart to display a gauge type chart with a title and a single series representing humidity. We set the initial data value to 0.
We establish a WebSocket connection to ws://localhost:1234
, assuming the server is running on the same machine and port. The onopen
event listener confirms that the WebSocket connection is established. When a new message is received (onmessage
event), we parse the data and update the chart's series with the new value using chart.series[0].points[0].update(value
).
Running the Application
To run the application, follow these steps:
- Save the server code to a file called server.js.
- Install the ws package by running npm install ws in the same directory as server.js.
- Start the websocket server by running node server.js.
- Save the HTML code to a file called index.html.
- Open a web browser and visit index.html.
- Open the browser console to view the WebSocket connection status and received data updates.
With the server running and the HTML page loaded, the gauge chart will update in real-time as the server sends random data to the clients. The needle on the gauge chart will reflect the new values received.
Integrating WebSocket with Highcharts allows us to create powerful and dynamic data visualization applications. By establishing a WebSocket connection between the server and the client and utilizing Highcharts' gauge chart, we can visualize real-time data updates in an intuitive and visually appealing manner. This enables us to build interactive dashboards for monitoring various types of real-time data, such as sensor readings, financial data, or performance metrics. Feel free to customize the code and explore different chart configurations to create your own real-time visualization solutions.
Posted on June 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.