Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <style>
- div.tooltip {
- position: absolute;
- text-align: center;
- width: 90px;
- height: 32px;
- padding: 2px;
- font: 12px sans-serif;
- background: lightsteelblue;
- border: 0px;
- border-radius: 4px;
- pointer-events: none;
- }
- </style>
- <title>JS Bin</title>
- </head>
- <body>
- <svg width="960" height="500"></svg>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>
- <script>
- function ready(fn) {
- if (document.readyState != 'loading'){
- fn();
- } else {
- document.addEventListener('DOMContentLoaded', fn);
- }
- }
- ready(init);
- function init() {
- let parseDate = d3.timeParse("%b-%y");
- function parsing(d) {
- d.date = parseDate(d.date);
- return d;
- }
- data = data.map(parsing);
- let svg = d3.select("svg");
- let margin = {top: 20, right: 20, bottom: 20, left: 40};
- let width = +svg.attr("width") - margin.left - margin.right;
- let height = +svg.attr("height") - margin.top - margin.bottom;
- let chart = svg
- .append('g')
- .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
- let x = d3
- .scaleTime()
- .domain(d3.extent(data, d => d.date))
- .range([0, width]);
- let y = d3
- .scaleLinear()
- .domain([0, d3.max(data, d => d.price)])
- .range([height, 0]);
- let xAxis = d3.axisBottom(x);
- let yAxis = d3.axisLeft(y);
- chart
- .append('g')
- .attr('transform', 'translate(0, ' + height + ')')
- .call(xAxis);
- chart
- .append('g')
- .call(yAxis);
- let priceLine = d3.line()
- .x(d => x(d.date))
- .y(d => y(d.price));
- let costLine = d3.line()
- .x(d => x(d.date))
- .y(d => y(d.cost))
- .curve(d3.curveMonotoneX);
- chart
- .append('path')
- .data([data])
- .attr('fill', 'none')
- .attr('stroke', 'darkred')
- .attr('stroke-width', 2)
- .attr('d', priceLine);
- chart
- .append('path')
- .datum(data)
- .attr('fill', 'none')
- .attr('stroke', 'steelblue')
- .attr('stroke-width', 2)
- .attr('d', costLine);
- chart
- .selectAll('dot')
- .data(data)
- .enter()
- .append('circle')
- .attr('r', 2)
- .attr('cx', d => x(d.date))
- .attr('cy', d => y(d.price))
- .attr('class', 'pricedots')
- .style('fill', 'darkred');
- let div = d3
- .select('body')
- .append('div')
- .attr('class', 'tooltip')
- .style('opacity', 0);
- let formatTime = d3.timeFormat('%b-%Y');
- chart
- .selectAll('.pricedots')
- .on('mouseover', d => {
- div
- .transition()
- .duration(200)
- .style('opacity', 0.9);
- div
- .html('date: ' + formatTime(d.date) + '<br/>' +
- 'price: ' + d.price)
- .style('left', (d3.event.pageX + 5) + 'px')
- .style('top', (d3.event.pageY - 35) + 'px');
- })
- .on('mouseout', d => {
- div
- .transition()
- .duration(500)
- .style("opacity", 0);
- });
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement