我正在查看d3 svg条形图上的示例(通过修改数据从Bar chart获取的示例)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id='Bar1'></div>
var tsv = "letter frequency\n" +
"django 12\n" +
"dictionary 33\n" +
"C 55\n" +
"D 100\n" +
"E 90\n" +
"F 320\n" +
"G 80\n" +
"H 10\n" +
"I 0\n" +
"J 0";
var margin1 = {top: 40, right: 20, bottom: 30, left: 40},
width1 = 460 //- margin.left - margin.right,
height1 = 200 //- margin.top - margin.bottom;
var formatPercent1 = d3.format("");
var x1 = d3.scale.ordinal()
.rangeRoundBands([0, width1], 0);
//.rangeRoundBands([width1, 0);
var y1 = d3.scale.linear()
.range([height1, 0]);
var xAxis1 = d3.svg.axis()
.scale(x1)
.orient("bottom");
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("left")
.tickFormat(formatPercent1);
var svg1 = d3.select("#Bar1").append("svg")
.attr("width", width1 + margin1.left + margin1.right)
.attr("height", height1 + margin1.top + margin1.bottom)
.append("g")
.attr("transform", "translate(" + margin1.left + "," + margin1.top + ")");
var data1 = d3.tsv.parse(tsv, type)
x1.domain(data1.map(function(d) { return d.letter; }));
y1.domain([0, d3.max(data1, function(d) { return d.frequency; })]);
svg1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height1 + ")")
.call(xAxis1);
svg1.append("g")
.attr("class", "y axis")
.call(yAxis1)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg1.selectAll(".bar")
.data(data1)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x1(d.letter); })
.attr("width", x1.rangeBand())
.attr("y", function(d) { return y1(d.frequency); })
.attr("height", function(d) { return height1 - y1(d.frequency); })
function type(d) {
d.frequency = +d.frequency;
return d;
}
,上面代码的输出如下图所示。
如果我们观察到由“F 320 \ n”表示的条形,它超过y轴值(y轴上的最大值为300)。
有人可以告诉我是否有可能在y轴上显示320,以便显示由“F”表示的条而不超过Y轴最大值?
答案 0 :(得分:1)
您可以在最大值
处为轴添加特定刻度// Get ticks
var ticks = y1.ticks();
// Add a tick at y max
ticks.push(d3.max(data1, function(d) { return d.frequency; }));
// Add all ticks to the y axis
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("left")
.tickFormat(formatPercent1)
.tickValues(ticks);
或者您可以手动设置所有刻度:
// Add custom ticks to the y axis
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("left")
.tickFormat(formatPercent1)
.tickValues([80, 160, 240, 320]);