[英]How to add tooltip to a react + d3 grouped and stacked bar chart?
[英]How to make a react + d3 stacked bar chart grouped?
我正在使用 react + d3 創建一個堆疊和分組的條形圖,我將其堆疊但找不到如何將其分組?
我想要這樣的圖片
數據看起來像:
const data = [
{
name: "Brand 1",
Affiliate: 10,
Social: 20,
Media: 30
},
{
name: "Brand 2",
Affiliate: 20,
Social: 40,
Media: 60
},
{
name: "Brand 3",
Affiliate: 30,
Social: 45,
Media: 80
},
{
name: "Brand 4",
Affiliate: 40,
Social: 60,
Media: 100
},
{
name: "Brand 5",
Affiliate: 50,
Social: 80,
Media: 120
}
];
生成堆棧的部分如下所示:
const stackGenerator = stack().keys(keys);
const layers = stackGenerator(data);
任何使其堆疊+分組的幫助將不勝感激
基於這個例子,這樣的事情應該可以工作:你可以在這里找到整個例子。
const data = [
{
name: "Brand 1",
type: 1,
Affiliate: 10,
Social: 20,
Media: 30
},
{
name: "Brand 1",
type: 2,
Affiliate: 20,
Social: 40,
Media: 60
},
{
name: "Brand 2",
type: 1,
Affiliate: 30,
Social: 45,
Media: 80
},
{
name: "Brand 3",
type: 1,
Affiliate: 40,
Social: 60,
Media: 100
},
{
name: "Brand 3",
type: 2,
Affiliate: 50,
Social: 80,
Media: 120
}
];
制作兩個嵌套軸:
const x0Scale = scaleBand()
.domain(data.map((d) => d.name))
.range([0, width])
.padding(0.46);
const x1Scale = scaleBand()
.domain(data.map((d) => d.type))
.rangeRound([0, x0Scale.bandwidth()])
.padding(0.12);
並使條的寬度取決於最小軸的寬度:
.attr("x", (sequence) => x0Scale(sequence.data.name)
+ x1Scale(sequence.data.type))
.attr("width", x1Scale.bandwidth())
這產生了以下圖片:
唯一的缺點是該解決方案假設每個組都有相同的成員 - 否則它不會吸引他們,正如您從“品牌 2”右側的間隙中看到的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.