Ось гистограммы D3 неправильно масштабируется - PullRequest
0 голосов
/ 24 января 2020

У меня есть код, показанный в следующем фрагменте для создания гистограммы в D3 JS.

var chartItems = [{
    "time": "10:05",
    "count": "5"
  },
  {
    "time": "10:10",
    "count": "6"
  },
  {
    "time": "10:15",
    "count": "4"
  },
  {
    "time": "10:20",
    "count": "3"
  },
  {
    "time": "10:25",
    "count": 0
  },
  {
    "time": "10:30",
    "count": "4"
  },
  {
    "time": "10:35",
    "count": "1"
  },
  {
    "time": "10:40",
    "count": "44"
  },
  {
    "time": "10:45",
    "count": "55"
  },
  {
    "time": "10:50",
    "count": "78"
  },
  {
    "time": "10:55",
    "count": "84"
  },
  {
    "time": "11:00",
    "count": "120"
  }
];




var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>" + d.time + ":</strong> <span style='color:red'>" + d.count + "</span>";
  });

var margin = {
  top: 50,
  right: 20,
  bottom: 100,
  left: 60
};
width = 360 - margin.left - margin.right;
height = 400 - margin.top - margin.bottom;
x = d3.scale.ordinal().rangeRoundBands([0, width], 0.5);
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")
  .ticks(5)
  .innerTickSize(-width)
  .outerTickSize(0)
  .tickPadding(10);
x.domain(chartItems.map(function(item) {
  return item.time;
}));

y.domain([0, d3.max(chartItems, function(item) {
  return item.count;
})]);

var svg = d3.select('#chart-container')
  .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 + ")");


svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0, " + height + ")")
  .call(xAxis)
  .selectAll("text")
  .style("text-anchor", "middle")
  .attr("dx", "-0.5em")
  .attr("dy", "-.55em")
  .attr("y", 30)
  .attr("transform", "rotate(-30)");

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 5)
  .attr("dy", "0.8em")
  .attr("text-anchor", "end");
svg.call(tip);

svg.selectAll("bar")
  .data(chartItems)
  .enter()
  .append("rect")
  .style("fill", 'red')
  .attr("x", function(d) {
    return x(d.time);
  })
  .attr("width", x.rangeBand())
  .attr("y", function(d) {
    return y(d.count);

  })
  .attr("height", function(d) {
    return height - y(d.count);
  })
  .on('mouseover', tip.show)
  .on('mouseout', tip.hide);
.chart-container {
  float: left;
}

.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: #555555;
  color: #fff;
  border-radius: 2px;
}


/* Creates a small triangle extender for the tooltip */

.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: #555555;
  content: "\25BC";
  position: absolute;
  text-align: center;
}


/* Style northward tooltips differently */

.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}

body,
html {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

.graph {
  width: auto;
}

.axis {
  font: 10px Georgia, Arial, sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #dadada;
  shape-rendering: crispEdges;
}

#chart-container {
  margin-top: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.js"></script>
<div id="chart-container"></div>

Здесь я сталкиваюсь с проблемой, ось Y показывает только до 80, тогда как мое максимальное значение 120. Как я могу это исправить ?

Я добавил скрипку: https://jsfiddle.net/fz47vnL9/1/

1 Ответ

3 голосов
/ 24 января 2020

Ваш счетчик элементов - это строки, поэтому вам нужно преобразовать их в числа с parseFloat, чтобы найти правильное максимальное значение:

y.domain([0, d3.max(chartItems, function(item) {
    return parseFloat(item.count);
})]);
...