我正在創建一個 D3 面積圖,該面積顯示在線上方而不是下方。
面積出現在線上方的面積圖
這是一個小提琴:https : //jsfiddle.net/8xsrmgzw/
//Read the data
d3.csv("https://raw.githubusercontent.com/kalidogg/UCB/main/DebtPenny6.csv",
// When reading the csv, I must format variables:
function(d){
return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.value }
},
// Now I can use this dataset:
function(data) {
// Add X axis --> it is a date format
var x = d3.scaleTime()
.domain(d3.extent(data, function(d) { return d.date; }))
.range([ 0, width ]);
svg.append("g")
.attr("transform", "translate(0," height ")")
.call(d3.axisBottom(x));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return d.value; })])
.range([ height, 0 ]);
svg.append("g")
.call(d3.axisLeft(y));
// Add the area
svg.append("path")
.datum(data)
.attr("fill", "#cce5df")
.attr("stroke", "#69b3a2")
.attr("stroke-width", 1.5)
.attr("d", d3.area()
.x(function(d) { return x(d.date) })
.y0(y(0))
.y1(function(d) { return y(d.value) })
)
})
</script>
謝謝。
uj5u.com熱心網友回復:
有幾個問題。首先,您需要在繪制區域之前按日期對資料進行排序。其次,您的資料集包含空值。在下面的示例中,我已將它們過濾掉,但您可以考慮執行類似 這些 示例的操作來指示資料丟失的位置。
此外,在該區域上設定筆觸顏色將創建該區域的輪廓,包括側面和底部。如果您只想要一條勾勒出該區域頂部的線條,那么您可以添加一個單獨的路徑并用于area.lineY1()獲取該區域頂部線條的線條生成器。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://d3js.org/d3.v7.js"></script>
</head>
<body>
<div id="chart"></div>
<script>
d3.csv("https://raw.githubusercontent.com/kalidogg/UCB/main/DebtPenny6.csv", function(d) {
return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.value }
}).then(chart);
function chart(data) {
// set up
const margin = { top: 10, bottom: 30, left: 50, right: 10};
const width = 600 - margin.left - margin.right;
const height = 200 - margin.top - margin.bottom;
const svg = d3.select('#chart')
.append('svg')
.attr('width', width margin.left margin.right)
.attr('height', height margin.top margin.bottom);
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
// filter and sort data
data = data
.filter(d => !isNaN(d.value))
.sort((a, b) => d3.ascending(a.date, b.date));
// scales
const x = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, width]);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([height, 0]);
// area generator
const area = d3.area()
.x(d => x(d.date))
.y0(y(0))
.y1(d => y(d.value));
// Add the area and top line
g.append("path")
.datum(data)
.attr("fill", "#cce5df")
.attr("d", area);
g.append("path")
.datum(data)
.attr("stroke", "#69b3a2")
.attr("stroke-width", 1.5)
.attr("fill", "none")
.attr("d", area.lineY1());
// Axes
g.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x));
g.append("g")
.call(d3.axisLeft(y)
.tickFormat(d3.format('~s'))
.tickSizeOuter(0));
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326040.html
標籤:javascript html d3.js 图表 面积图
