в D3 js подогнать как на картинке ?помогите разобраться

282
13 октября 2017, 15:02

var JSONdata={ 
  "measurementPoints": [ 
    { 
      "measurementValue": 84.684, 
      "measurementDateTime": "2016-06-09T17:05:00" 
    }, 
    { 
      "measurementValue": 84.684, 
      "measurementDateTime": "2016-06-09T17:05:00" 
    }, 
    { 
      "measurementValue": 86.099, 
      "measurementDateTime": "2016-06-09T17:10:00" 
    }, 
    { 
      "measurementValue": 86.572, 
      "measurementDateTime": "2016-06-09T17:15:00" 
    }, 
    { 
      "measurementValue": 86.871, 
      "measurementDateTime": "2016-06-09T17:20:00" 
    }, 
    { 
      "measurementValue": 86.961, 
      "measurementDateTime": "2016-06-09T17:25:00" 
    }, 
    { 
      "measurementValue": 87.224, 
      "measurementDateTime": "2016-06-10T09:10:00" 
    }, 
    { 
      "measurementValue": 87.235, 
      "measurementDateTime": "2016-06-10T09:15:00" 
    }, 
    { 
      "measurementValue": 87.098, 
      "measurementDateTime": "2016-06-10T09:20:00" 
    }, 
    { 
      "measurementValue": 87.258, 
      "measurementDateTime": "2016-06-10T09:25:00" 
    }, 
    { 
      "measurementValue": 87.474, 
      "measurementDateTime": "2016-06-10T09:30:00" 
    }, 
    { 
      "measurementValue": 87.978, 
      "measurementDateTime": "2016-06-10T09:35:00" 
    }, 
    { 
      "measurementValue": 87.508, 
      "measurementDateTime": "2016-06-10T09:40:00" 
    }, 
    { 
      "measurementValue": 87.451, 
      "measurementDateTime": "2016-06-10T09:45:00" 
    }, 
    { 
      "measurementValue": 87.465, 
      "measurementDateTime": "2016-06-10T09:50:00" 
    }, 
    { 
      "measurementValue": 87.483, 
      "measurementDateTime": "2016-06-10T09:55:00" 
    }, 
    { 
      "measurementValue": 87.489, 
      "measurementDateTime": "2016-06-10T10:00:00" 
    }, 
    { 
      "measurementValue": 87.517, 
      "measurementDateTime": "2016-06-10T10:05:00" 
    }, 
    { 
      "measurementValue": 87.132, 
      "measurementDateTime": "2016-06-10T10:10:00" 
    }, 
    { 
      "measurementValue": 87.622, 
      "measurementDateTime": "2016-06-10T10:15:00" 
    }, 
    { 
      "measurementValue": 87.298, 
      "measurementDateTime": "2016-06-10T10:20:00" 
    }, 
    { 
      "measurementValue": 87.669, 
      "measurementDateTime": "2016-06-10T10:25:00" 
    }, 
    { 
      "measurementValue": 87.967, 
      "measurementDateTime": "2016-06-10T10:30:00" 
    }, 
    { 
      "measurementValue": 87.483, 
      "measurementDateTime": "2016-06-10T10:35:00" 
    }, 
    { 
      "measurementValue": 87.298, 
      "measurementDateTime": "2016-06-10T10:40:00" 
    }, 
    { 
      "measurementValue": 86.9, 
      "measurementDateTime": "2016-06-10T10:45:00" 
    }, 
    { 
      "measurementValue": 87.904, 
      "measurementDateTime": "2016-06-10T10:50:00" 
    }, 
    { 
      "measurementValue": 87.118, 
      "measurementDateTime": "2016-06-10T10:55:00" 
    }, 
    { 
      "measurementValue": 87.597, 
      "measurementDateTime": "2016-06-10T11:00:00" 
    }, 
    { 
      "measurementValue": 86.986, 
      "measurementDateTime": "2016-06-10T11:05:00" 
    }, 
    { 
      "measurementValue": 87.294, 
      "measurementDateTime": "2016-06-10T11:10:00" 
    }, 
    { 
      "measurementValue": 87.451, 
      "measurementDateTime": "2016-06-10T11:15:00" 
    }, 
    { 
      "measurementValue": 87.377, 
      "measurementDateTime": "2016-06-10T11:20:00" 
    }, 
    { 
      "measurementValue": 87.627, 
      "measurementDateTime": "2016-06-10T11:25:00" 
    } 
  ], 
  "sensorId": 145 
}; 
 
 
 
	// This is the format our dates are in, e.g 23/05/2014 
	var timeFormat = d3.time.format('%Y-%m-%dT%H:%M:%S'); 
 
	var dates = [], 
	    dateStrings = [], 
	    temps = []; 
 
var frequencyData=[]; 
 
	JSONdata.measurementPoints.forEach(function(d) { 
 
		// Keep array of original date strings 
		dateStrings.push(d.measurementDateTime); 
 
		// Convert date string into JS date, add it to dates array 
		dates.push(timeFormat.parse(d.measurementDateTime)); 
 
		// Add high temperature to temps array 
		temps.push(+d.measurementValue); 
 
	}); 
  //set up chart base details 
  var margin = {top: 10, right: 30, bottom: 100, left: 40}, 
    margin2 = {top: 250, right: 10, bottom: 20, left: 40}, 
    width = 960 - margin.left - margin.right, 
    height = 500 - margin.top - margin.bottom, 
    height2 = 500 - margin2.top - margin2.bottom; 
  //div container for the chart 
	var container = d3.select('#temp-chart'); 
  //creating svg element 
	var svg = container.append('svg') 
		.attr('width', width) 
		.attr('height', height); 
 
  //add graphichal object for later usage 
	var defs = svg.append('defs'); 
 
	// clipping area for drawing 
	defs.append('clipPath')	 
		.attr('id', 'plot-area-clip-path') 
		.append('rect') 
			.attr({ 
				x: margin.left, 
				y: margin.top, 
				width: width - margin.right - margin.left, 
				height: height - margin.top - margin.bottom 
			}); 
 
	// Invisible background rect to capture all zoom events 
	var backRect = svg.append('rect') 
		.style('stroke', 'none') 
		.style('fill', '#FFF') 
		.style('fill-opacity', 0) 
		.attr({ 
			x: margin.left, 
			y: margin.top, 
			width: width - margin.right - margin.left, 
			height: height - margin.top - margin.bottom, 
			'pointer-events': 'all' 
		}); 
 
	var axes = svg.append('g') 
		.attr('pointer-events', 'none') 
		.style('font-size', '11px'); 
 
	var chart = svg.append('g') 
		.attr('class', 'plot-area') 
		.attr('pointer-events', 'none') 
		.attr('clip-path', 'url(#plot-area-clip-path)'); 
 
	// x scale 
	var xScale = d3.time.scale() 
		.range([margin.left, width - margin.right]) 
		.domain(d3.extent(dates)); 
 
	// Calculate the range of the temperature data 
	var yExtent = d3.extent(temps); 
	var yRange = yExtent[1] - yExtent[0]; 
 
	// Adjust the lower and upper bounds to force the data 
	// to fit into the y limits nicely 
	yExtent[0] = yExtent[0] - yRange * 0.1; 
	yExtent[1] = yExtent[1] + yRange * 0.1; 
 
	// the y scale 
	var yScale = d3.scale.linear() 
		.range([height - margin.bottom, margin.top]) 
		.domain(yExtent); 
 
	// x axis 
	var xAxis = d3.svg.axis() 
		.orient('bottom') 
		.outerTickSize(0) 
		.innerTickSize(0) 
		.scale(xScale); 
 
	// y axis 
	var yAxis = d3.svg.axis() 
		.orient('left') 
		.outerTickSize(0) 
		.innerTickSize(- (width - margin.left - margin.right))  // trick for creating quick gridlines 
		.scale(yScale); 
 
	var yAxis2 = d3.svg.axis() 
		.orient('right') 
		.outerTickSize(0) 
		.innerTickSize(0) 
		.scale(yScale); 
 
	// Add the x axis to the chart 
	var xAxisEl = axes.append('g') 
		.attr('class', 'x-axis') 
		.attr('transform', 'translate(' + 0 + ',' + (height - margin.bottom) + ')') 
		.call(xAxis); 
 
	// Add the y axis to the chart 
	var yAxisEl = axes.append('g') 
		.attr('class', 'y-axis') 
		.attr('transform', 'translate(' + margin.left + ',' + 0 + ')') 
		.call(yAxis); 
 
	// Add the y axis to the chart 
	var yAxisEl2 = axes.append('g') 
		.attr('class', 'y-axis right') 
		.attr('transform', 'translate(' + (width - margin.right) + ',' + 0 + ')') 
		.call(yAxis2); 
 
	// Format y-axis gridlines 
	yAxisEl.selectAll('line') 
		.style('stroke', '#BBB') 
		.style('stroke-width', '1px') 
		.style('shape-rendering', 'crispEdges'); 
 
 
	// Start data as a flat line at the average 
	var avgTempY = yScale(d3.mean(temps)); 
 
	// Path generator function for our data 
	var pathGenerator = d3.svg.line() 
		.x(function(d, i) { 
      return xScale(dates[i]); }) 
		.y(function(d, i) { return yScale(temps[i]); }); 
 
	// Series container element 
	var series = chart.append('g'); 
 
	// Add the temperature series path to the chart 
	var path = series.append('path') 
		.attr('vector-effect', 'non-scaling-stroke') 
		.style('fill', 'none') 
		.style('stroke', 'red') 
		.style('stroke-width', '1px') 
    .attr("class", "line") 
		.attr('d', pathGenerator(dates)); 
 
 
	// Add zooming and panning functionality, only along the x axis 
	var zoom = d3.behavior.zoom() 
		.scaleExtent([1, 12]) 
		.x(xScale) 
		.on('zoom', function zoomHandler() { 
      debugger; 
			axes.select('.x-axis') 
				.call(xAxis); 
			series.attr('transform', 'translate(' + d3.event.translate[0] + ',0) scale(' + d3.event.scale + ',1)'); 
 
		}); 
 
 
	// The backRect captures zoom/pan events 
	backRect.call(zoom); 
 
 
	// Function for resetting any scaling and translation applied 
	// during zooming and panning. Returns chart to original state. 
	function resetZoom() { 
 
		zoom.scale(1); 
		zoom.translate([0, 0]); 
		 
		// Set x scale domain to the full data range 
		xScale.domain(d3.extent(dates)); 
 
		// Update the x axis elements to match 
		axes.select('.x-axis') 
			.transition() 
			.call(xAxis); 
 
		// Remove any transformations applied to series elements 
		series.transition() 
			.attr('transform', "translate(0,0) scale(1,1)"); 
     
    path.attr('d', pathGenerator(dates)); 
   
    xAxis.scale(xScale); 
    xAxisEl.call(xAxis); 
 
	}; 
 
// Call resetZoom function when the button is clicked 
d3.select("#reset-zoom").on("click", resetZoom); 
// Call scaleMonth function when the button is clicked 
d3.select("#monthButton").on("click", scaleMonth); 
	// Call scaleMonth function when the button is clicked 
d3.select("#dayButton").on("click", scaleDay); 
	// Call scaleMonth function when the button is clicked 
d3.select("#hourButton").on("click", scaleHour); 
d3.select("#okButton").on("click", scaleFrequency); 
	// Active point element 
	var activePoint = svg.append('circle') 
		.attr({ 
			cx: 0, 
			cy: 0, 
			r: 5, 
			'pointer-events': 'none' 
		}) 
		.style({ 
			stroke: 'none', 
			fill: 'red', 
			'fill-opacity': 0 
		}); 
 
 
	// Set container to have relative positioning. This allows us to easily 
	// position the tooltip element with absolute positioning. 
	container.style('position', 'relative'); 
 
	// Create the tooltip element. Hidden initially. 
	var tt = container.append('div') 
		.style({padding: '5px', 
			border: '1px solid #AAA', 
			color: 'black', 
			position: 'absolute', 
			visibility: 'hidden', 
			'background-color': '#F5F5F5' 
		}); 
debugger; 
 
 
	// Function for hiding the tooltip 
	function hideTooltip() { 
		tt.style('visibility', 'hidden'); 
		activePoint.style('fill-opacity', 0); 
 
	} 
 
 
	// Function for showing the tooltip 
	function showTooltip() { 
		tt.style('visibility', 'visible'); 
		activePoint.style('fill-opacity', 1); 
 
	} 
 
 
	// Tooltip content formatting function 
	function tooltipFormatter(date, temp) { 
 
		var dateFormat = d3.time.format('%d %b %Y %X'); 
		return dateFormat(date) + '<br><b>' + temp.toFixed(1) + '°F'; 
 
	} 
 
 
 
	backRect.on('mousemove', function() { 
		// Coords of mousemove event relative to the container div 
		var coords = d3.mouse(container.node()); 
 
		// Value on the x scale corresponding to this location 
		var xVal = xScale.invert(coords[0]); 
		var d = new Date(xVal.getTime()); 
    d.setSeconds(0); 
    if(frequencyData.length!==0) 
    d.setMinutes(0); 
		// Format the date object as a date string matching our original data 
		var date = timeFormat(d); 
    debugger; 
		// Find the index of this date in the array of original date strings 
		var i = dateStrings.indexOf(date); 
 
		// Does this date exist in the original data? 
		var dateExists = i > -1; 
 
		// If not, hide the tooltip and return from this function 
		if (!dateExists) { 
			hideTooltip(); 
			return; 
		} 
 
		// If we are here, the date was found in the original data. 
		// Proceed with displaying tooltip for of the i-th data point. 
 
		// Get the i-th date value and temperature value. 
		var _date = dates[i], 
		    _temp = temps[i]; 
 
		// Update the position of the activePoint element 
		activePoint.attr({ 
			cx: xScale(_date), 
			cy: yScale(_temp) 
		}); 
 
		// Update tooltip content 
		tt.html(tooltipFormatter(_date, _temp)); 
 
		// Get dimensions of tooltip element 
		var dim = tt.node().getBoundingClientRect(); 
 
		// Update the position of the tooltip. By default, above and to the right 
		// of the mouse cursor. 
		var tt_top = coords[1] - dim.height - 10, 
		    tt_left = coords[0] + 10; 
 
		// If right edge of tooltip goes beyond chart container, force it to move 
		// to the left of the mouse cursor. 
		if (tt_left + dim.width > width) 
			tt_left = coords[0] - dim.width - 10; 
 
		tt.style({ 
			top: tt_top + 'px', 
			left: tt_left + 'px' 
		}); 
		 
		// Show tooltip if it is not already visible 
		if (tt.style('visibility') != 'visible') 
			showTooltip(); 
 
	}); 
 
 
	// Add mouseout event handler 
	backRect.on('mouseout', hideTooltip); 
 
//brush area 
var x2Scale = d3.time.scale().range([-30, width - 120]); 
var y2Scale=d3.scale.linear().range([100, 0]); 
var xAxis2 = d3.svg.axis().scale(x2Scale).orient("bottom"); 
 
var brush = d3.svg.brush() 
    .x(x2Scale) 
    .on("brush", brushed); 
 
 
var contextLine = d3.svg.line() 
    .x(function(d) { return x2Scale(d.measurementDateTime); }) 
    .y(function(d) { return y2Scale(d.measurementValue); }) 
    .defined(function(d) { return d.measurementValue; }); 
 
var context = svg.append("g") 
    .attr("class", "context") 
    .attr("transform", "translate(" + 50 + "," +250 + ")"); 
 
x2Scale.domain(xScale.domain()); 
y2Scale.domain(yScale.domain()); 
 
context.append("g") 
        .attr("class", "x axis"); 
 
context.select('.x.axis') 
      .attr("transform", "translate(0," + 120 + ")") 
      .call(xAxis2); 
 
 
function renderBrushLines() { 
  var chartEl = context; 
  var chartLine = contextLine; 
 
  if(frequencyData.length===0){ 
    for(var i=0;i<JSONdata.measurementPoints.length;i++){ 
      JSONdata.measurementPoints[i].measurementDateTime=new Date(JSONdata.measurementPoints[i].measurementDateTime); 
    } 
  } 
  var line = chartEl.selectAll('path.line') 
                    .data([frequencyData.length===0?JSONdata.measurementPoints:frequencyData]); 
 
  line.enter().append('path') 
        .attr("transform", "translate(-90," + 60 + ")") 
        .attr("class", "line"); 
 
  line.transition() 
            .attr('d', function(d) { 
    
    return chartLine(d); }); 
 
  line.exit().remove(); 
}; 
 
function renderBrush() { 
  if (d3.select('g.brush').empty()) { 
 
    renderBrushLines(); 
 
    context.append("g") 
        .attr("class", "x brush") 
        .call(brush) 
      .selectAll("rect") 
        .attr("y", 60) 
        .attr("height", 57); 
  } else { 
    renderBrushLines(); 
  }; 
} 
 
function updateChart(startDate,endDate){ 
  var datesBetweenRange=[]; 
   
  var i=0; 
  while(JSONdata.measurementPoints[i]&&JSONdata.measurementPoints[i].measurementDateTime<=endDate){     
    if(JSONdata.measurementPoints[i].measurementDateTime>=startDate){ 
      datesBetweenRange.push(JSONdata.measurementPoints[i].measurementDateTime); 
    } 
    i++; 
  } 
  if(datesBetweenRange.length>0){ 
    chart.select('path').attr('d',pathGenerator(datesBetweenRange)); 
    chart.select(".x.axis").call(xAxis); 
  } 
  path.attr('d', pathGenerator(dates)); 
   
  xAxis.scale(xScale); 
  xAxisEl.call(xAxis); 
} 
 
 
function scaleMonth(){ 
  var endDate=JSONdata.measurementPoints[JSONdata.measurementPoints.length-1].measurementDateTime; 
  var startDate=new Date(); 
  startDate.setMonth(endDate.getMonth()-1); 
  updateChart(startDate,endDate); 
} 
 
function scaleDay(){ 
  var endDate=JSONdata.measurementPoints[JSONdata.measurementPoints.length-1].measurementDateTime; 
  var startDate=new Date(endDate.getTime() - 24*60*60*1000); 
  updateChart(startDate,endDate); 
} 
 
function scaleHour(){ 
  var endDate=JSONdata.measurementPoints[JSONdata.measurementPoints.length-1].measurementDateTime; 
  var startDate=new Date(endDate.getTime() - 60*60*1000); 
  var userTimezoneOffset = new Date().getTimezoneOffset()*60000; 
   
  brush.extent([new Date(startDate.getTime() + userTimezoneOffset), new Date(endDate.getTime() + userTimezoneOffset)]); 
  context.select('.brush').call(brush); 
  brushed(); 
} 
 
function scaleFrequency(){ 
  frequencyData=[]; 
   
  var interval=1000*60*60; 
  var max=JSONdata.measurementPoints[1].measurementDateTime.getTime()+interval; 
   
  //starting point 
  frequencyData.push(JSONdata.measurementPoints[0]); 
   
  var sumTemp=0; 
  var counter=0; 
  for(var i=1;i<JSONdata.measurementPoints.length;i++){ 
    if(JSONdata.measurementPoints[i].measurementDateTime.getTime()<max){ 
          sumTemp+=JSONdata.measurementPoints[i].measurementValue; 
          counter++; 
     }else{ 
          //the last valid time data and the avarage 
          var obj={measurementDateTime:JSONdata.measurementPoints[i-1].measurementDateTime,measurementValue:sumTemp/counter}; 
          frequencyData.push(obj); 
          //clear and start again 
          sumTemp=JSONdata.measurementPoints[i].measurementValue; 
          counter=1; 
          max=JSONdata.measurementPoints[i].measurementDateTime.getTime()+interval; 
      } 
  } 
  dateStrings=[]; 
  dates=[]; 
  temps=[]; 
  frequencyData.forEach(function(d) { 
		  // Keep array of original date strings 
		  dateStrings.push(timeFormat(d.measurementDateTime)); 
		  // Convert date string into JS date, add it to dates array 
		  dates.push(d.measurementDateTime); 
		  // Add high temperature to temps array 
		  temps.push(+d.measurementValue); 
 
	}); 
  var userTimezoneOffset = new Date().getTimezoneOffset()*60000; 
  var startDate=new Date(frequencyData[0].measurementDateTime.getTime() + userTimezoneOffset); 
  var endDate=new Date(frequencyData[frequencyData.length-1].measurementDateTime.getTime() + userTimezoneOffset); 
  xScale.domain([startDate, endDate]); 
  resetZoom();  
   
  renderBrush(); 
} 
 
 
function brushed() { 
  console.log(brush.extent()); 
   
  var startDate=new Date(brush.extent()[0]); 
  var endDate=new Date(brush.extent()[1]); 
  xScale.domain(brush.empty() ? x2Scale.domain() : brush.extent()); 
   
  updateChart(startDate,endDate); 
} 
 
 
renderBrush();
.brush .extent { 
  stroke: #FFF; 
  shape-rendering: crispEdges; 
} 
.line { 
  fill: none; 
  stroke-width: 1px; 
  clip-path: url(#plot-area-clip-path); 
  stroke: red; 
 
} 
.line:nth-of-type(2) { 
  stroke: blue; 
} 
 
.axis path, 
.axis line { 
  fill: none; 
  stroke: #000; 
  shape-rendering: crispEdges; 
} 
 
.brush .extent { 
  stroke: #fff; 
  fill-opacity: .125; 
  shape-rendering: crispEdges; 
}
<!DOCTYPE html> 
<html > 
<head> 
  <meta charset="UTF-8"> 
  <title>A Pen by  Laszlo Peter</title> 
   
   
   
      <link rel="stylesheet" href="css/style.css"> 
 
   
</head> 
 
<body> 
  <button type="button" id="reset-zoom">Reset zoom</button> 
<button type="button" id="monthButton">1m</button> 
<button type="button" id="weekButton">1w</button> 
<button type="button" id="dayButton">1d</button> 
<button type="button" id="hourButton">1h</button> 
From: <input type="datetime-local" name="fromDate"> 
To: <input type="datetime-local" name="toDate"> 
 
Freq: <input type="number" name="frequency" min="1" max="99"> 
<select> 
  <option value="min">Min</option> 
  <option value="hour">Hour</option> 
  <option value="day">Day</option> 
  <option value="week">Week</option> 
</select> 
<button type="button" id="okButton">ok</button> 
<div id="temp-chart"></div> 
  <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js'></script> 
 
    <script  src="js/index.js"></script> 
 
</body> 
</html>

READ ALSO
Как выровнять форму подачи заявки?

Как выровнять форму подачи заявки?

Есть форма и текст которую надо разместить как на картинкеНикак не могу выровнять как надо

244
печать страницы нажатием enter

печать страницы нажатием enter

Есть вот такой код, который при нажатии кнопки выводит в новой вкладке шаблон на печатьстоит задача делать то же самое, но при нажатии кнопки...

446