如何在d3中向轴添加离散标签?
我正在尝试使用d3 v4创建带有离散X轴标签的折线图,但失败了。线链接的标签顺序根本不符合我在图形上放置的标签。
以下是一些用于生成图形的代码。
// 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"
}
]
反正有解决此问题的方法吗?
答案 0 :(得分:1)
仅设置序数标度的域是不够的。您必须根据所需的顺序(即秤的域)对数据进行排序。
例如:
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>