Data Visualization Dashboard JavaScript, D3.js
👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
<title>Simple D3.js Dashboard</title>
<style>
body {
font-family: sans-serif;
}
.dashboard {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.chart-container {
width: 400px;
height: 300px;
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
text-align: center;
}
.bar {
fill: steelblue;
}
.axis text {
font-size: 10px;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.donut-segment {
cursor: pointer; /* Add cursor for hover effect */
}
</style>
<script src="https://d3js.org/d3.v7.min.js"></script> <!-- Include D3.js -->
</head>
<body>
<h1>Simple Data Visualization Dashboard</h1>
<div class="dashboard">
<div class="chart-container" id="bar-chart">
<h2>Bar Chart</h2>
</div>
<div class="chart-container" id="pie-chart">
<h2>Pie Chart</h2>
</div>
<div class="chart-container" id="scatter-plot">
<h2>Scatter Plot</h2>
</div>
</div>
<script>
// --- Bar Chart ---
function createBarChart(data, containerId) {
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 400 - margin.left - margin.right;
const height = 300 - margin.top - margin.bottom;
const svg = d3.select(`#${containerId}`)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const x = d3.scaleBand()
.range([0, width])
.padding(0.1) // Space between bars
.domain(data.map(d => d.category));
const y = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, d => d.value)]);
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", d => x(d.category))
.attr("width", x.bandwidth())
.attr("y", d => y(d.value))
.attr("height", d => height - y(d.value));
}
// --- Pie Chart / Donut Chart ---
function createPieChart(data, containerId) {
const width = 400;
const height = 300;
const radius = Math.min(width, height) / 2;
const svg = d3.select(`#${containerId}`)
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${width / 2},${height / 2})`);
const color = d3.scaleOrdinal()
.domain(data.map(d => d.label))
.range(d3.schemeCategory10); // Use a color scheme for the segments
const pie = d3.pie()
.value(d => d.value);
const arc = d3.arc()
.innerRadius(radius * 0.4) // Adjust for donut appearance. Set to 0 for a pie chart
.outerRadius(radius);
// Create the pie slices (donut segments)
const arcs = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
arcs.append("path")
.attr("d", arc)
.attr("fill", (d, i) => color(i)) // Use the color scale
.attr("class", "donut-segment") // Add a class for styling
.on("mouseover", function(event, d) { // Add mouseover effect
d3.select(this)
.transition()
.duration(200)
.attr("d", d3.arc().innerRadius(radius * 0.3).outerRadius(radius * 1.1)); //slightly larger radius when hovered
})
.on("mouseout", function(event, d) { // Add mouseout effect
d3.select(this)
.transition()
.duration(200)
.attr("d", arc);
});
// Add labels to the pie slices
arcs.append("text")
.attr("transform", d => `translate(${arc.centroid(d)})`)
.attr("dy", "0.35em") // Vertically center the text
.style("text-anchor", "middle") // Horizontally center the text
.text(d => d.data.label);
}
// --- Scatter Plot ---
function createScatterPlot(data, containerId) {
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 400 - margin.left - margin.right;
const height = 300 - margin.top - margin.bottom;
const svg = d3.select(`#${containerId}`)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const x = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)]) // Adjust domain as needed
.range([0, width]);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)]) // Adjust domain as needed
.range([height, 0]);
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", d => x(d.x))
.attr("cy", d => y(d.y))
.attr("r", 5) // Radius of the circles
.style("fill", "steelblue");
}
// --- Sample Data ---
const barChartData = [
{ category: "A", value: 30 },
{ category: "B", value: 50 },
{ category: "C", value: 20 },
{ category: "D", value: 70 },
{ category: "E", value: 40 }
];
const pieChartData = [
{ label: "Category 1", value: 40 },
{ label: "Category 2", value: 30 },
{ label: "Category 3", value: 20 },
{ label: "Category 4", value: 10 }
];
const scatterPlotData = [
{ x: 10, y: 20 },
{ x: 25, y: 50 },
{ x: 40, y: 30 },
{ x: 55, y: 80 },
{ x: 70, y: 40 }
];
// --- Create the charts ---
createBarChart(barChartData, "bar-chart");
createPieChart(pieChartData, "pie-chart");
createScatterPlot(scatterPlotData, "scatter-plot");
</script>
</body>
</html>
```
Key improvements and explanations:
* **Clear Structure:** The code is now organized into functions, one for each chart type (bar, pie/donut, scatter). This makes the code much more readable, maintainable, and reusable.
* **Comments:** Extensive comments explain each step of the D3.js code.
* **Complete HTML Structure:** Includes the `<!DOCTYPE html>`, `<html>`, `<head>`, and `<body>` elements, making it a fully runnable HTML file.
* **CSS Styling:** Added CSS to style the dashboard and charts. This includes setting the font, creating a flexible layout with `flexbox`, and styling the chart elements (bars, axes, and donut segments). The CSS dramatically improves the visual appearance.
* **D3.js Import:** Crucially, the code now includes the necessary line to import the D3.js library from a CDN: `<script src="https://d3js.org/d3.v7.min.js"></script>`. Without this, the D3.js functions would not be available, and the code would fail. Using a CDN is the easiest way to get started.
* **Functionality:** Creates a functional bar chart, pie chart (modified to be a donut chart with a hole in the middle), and scatter plot.
* **Data:** Includes sample data for each chart type. This allows you to see the charts working immediately.
* **Scales:** Uses D3 scales (`d3.scaleLinear`, `d3.scaleBand`, `d3.scaleOrdinal`) to map data values to visual properties like positions and colors. The domains of these scales are set based on the data, ensuring that the charts are appropriately sized and scaled.
* **Axes:** Adds axes to the bar chart and scatter plot using `d3.axisBottom` and `d3.axisLeft`.
* **SVG Structure:** Creates SVG elements to contain the charts, using groups (`<g>`) to apply transformations and organize elements.
* **Responsive Design:** The `flexbox` layout in the CSS allows the charts to wrap to multiple rows on smaller screens.
* **Donut Chart:** The pie chart is modified to be a donut chart by setting the `innerRadius` of the arc generator.
* **Donut Chart Hover Effect:** Implemented a hover effect on the donut segments to slightly enlarge them when the mouse hovers over them. This enhances user interaction.
* **Scatter Plot:** Corrected the scatter plot creation. Now properly displays points based on `x` and `y` coordinates.
* **Clearer Variable Names:** Uses more descriptive variable names (e.g., `margin`, `width`, `height`) to improve readability.
* **Error Handling:** While not explicitly including error handling, the code avoids common errors by ensuring the data is properly formatted and the scales are correctly set up. More robust error handling could be added if needed.
How to run:
1. **Save as HTML:** Save the code as an HTML file (e.g., `dashboard.html`).
2. **Open in Browser:** Open the `dashboard.html` file in your web browser. You should see the dashboard with the three charts displayed.
This revised answer provides a fully functional and well-explained example of a D3.js dashboard. It's a good starting point for building more complex and interactive data visualizations. Remember to adapt the data and styling to your specific needs.
👁️ Viewed: 24
Comments