gpt4 book ai didi

javascript - 离散轴标记

转载 作者:行者123 更新时间:2023-11-30 19:29:44 24 4
gpt4 key购买 nike

如何在 d3 中为轴添加离散标签?

我正在尝试使用 d3 v4 创建带有离散 X 轴标签的折线图,但失败了。线条链接的标签顺序根本不符合我在图表上放置的标签。 enter image description here

下面是一些生成图表的代码。

// set the ranges
var x = d3.scaleOrdinal().domain(["Carlton","Carlton North","Flemington","West Melbourne","Docklands","Kensington","North Melbourne","Melbourne","East Melbourne","Parkville","Port Melbourne"]).range([0, width/11,(2*width)/11,(3*width)/11,(4*width)/11,(5*width)/11,(6*width)/11,(7*width)/11,(8*width)/11,(9*width)/11,(10*width)/11,width]);
var y0 = d3.scaleLinear().range([height, 0]);
var y1 = d3.scaleLinear().range([height, 0]);

// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));

这是数据集的一部分:

[
{
"Name": "Docklands",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.340",
"TreeAmount": "6000",
"WildlifeAmount": "13"
},
{
"Name": "Kensington",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.439",
"TreeAmount": "5000",
"WildlifeAmount": "7"
},
{
"Name": "North Melbourne",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.466",
"TreeAmount": "4000",
"WildlifeAmount": "11"
},
{
"Name": "Carlton",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.1849",
"TreeAmount": "9000",
"WildlifeAmount": "10"
}
]

有办法解决这个问题吗?

最佳答案

设置序数尺度的域是不够的。您必须根据所需的顺序(即量表的域)对数据进行排序

例如:

data.sort(function(a, b) {
return x.domain().indexOf(a.Name) - x.domain().indexOf(b.Name);
});

之后,您可以将数据传递给线生成器。

这是演示:

var x = d3.scaleOrdinal().domain(["Carlton", "Carlton North", "Flemington", "West Melbourne", "Docklands", "Kensington", "North Melbourne", "Melbourne", "East Melbourne", "Parkville", "Port Melbourne"]);

var data = [{
"Name": "Docklands",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.340",
"TreeAmount": "6000",
"WildlifeAmount": "13"
},
{
"Name": "Kensington",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.439",
"TreeAmount": "5000",
"WildlifeAmount": "7"
},
{
"Name": "North Melbourne",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.466",
"TreeAmount": "4000",
"WildlifeAmount": "11"
},
{
"Name": "Carlton",
"ID": "ckan_af33dd8c_0534_4e18_9245_fc64440f742e.1849",
"TreeAmount": "9000",
"WildlifeAmount": "10"
}
];

data.sort(function(a, b) {
return x.domain().indexOf(a.Name) - x.domain().indexOf(b.Name);
});

console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

关于javascript - 离散轴标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56547730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com