本文介绍了在d3.js中设置X轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的d3.js条形图中,我想要的X轴标签在垂直。我得到的标签水平,但问题是一些标签合并。

In my d3.js bar chart i want the X-axis labels to be in "vertical". I'm getting the labels in "Horizontal" but the problem is some of the labels getting merged.

<!DOCTYPE html>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}

.bar {
fill: red;
}

.x.axis path {
display: none;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("left");

var svg = d3.select("body").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 + ")");

d3.csv("ClassRoom.csv",type,function(error,data){
x.domain(data.map(function(d) { return d.Name; }));

y.domain([0, d3.max(data, function(d) { return d.Marks; })]);

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Marks");

svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.Name); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.Marks); })
.attr("height", function(d) { return height - y(d.Marks)});
});

function type(d) {
d.Marks = +d.Marks;
return d;
}

</script>

我的CSV档案是

Name,Marks
Sathesh,15
Somnath,45
Naresh,35
Venkat,25
Prabha,78
Dinesh,36


推荐答案

- 文本标签。假设您以这种方式创建X轴:

You will have to do that with the SVG-Text Labels. Assuming you create the X-Axis in this fashion:

        var xAxis = svg.append("g")
            .attr({
                "class":   "x axis",
                transform: "translate(0," + h + ")"
            })
            .call(xAxis);

您选择文本并应用转换:

You select the Text, and apply a transformation:

            xAxis.selectAll("text")
            .attr({
                transform: function (d) {
                    return "rotate(-60, 0, 0)";
                }
            });

您必须在旋转变换中调整0,0以满足您的需要。另外,我建议查看text-anchor属性。但这应该让你开始!

You will have to adjust the 0,0 in the rotate transformation to suit your needs. Also i recommend looking into the text-anchor attribute. But this should get you started!

这篇关于在d3.js中设置X轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:38