D3js делает высоту оси Y 100 - PullRequest
       23

D3js делает высоту оси Y 100

0 голосов
/ 21 сентября 2018

У меня есть этот линейный график D3js:

http://jsfiddle.net/90pgka1f/7/

Он работает нормально, за исключением того, что я хотел бы, чтобы диапазон по оси Y был от 0 до 100.В настоящее время вершина оси Y просто соответствует максимальному значению в наборе данных (65,55 в выборке)

var tokenPricesArray = [
    {"date":"18-Sep-18", "bitcoin_dominance":"55.55"},
    {"date":"19-Sep-18", "bitcoin_dominance":"65.55"},
];

// Set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

Как мне добиться этого, чтобы ось Y масштабировалась до 100?Спасибо!

1 Ответ

0 голосов
/ 21 сентября 2018

Просто установите домен вашей шкалы y на [0,100] вместо использования значения из ваших данных:

    y.domain([0, 100]);

Это будет гарантировать, что ось покрывает все 100% вместо 0 до максимума.из вашего набора данных.

В контексте:

var tokenPricesArray = [
    {"date":"18-Sep-18", "bitcoin_dominance":"55.55"},
    {"date":"19-Sep-18", "bitcoin_dominance":"65.55"},
];

// Milestones vs. Price
		
		// Set the dimensions of the canvas / graph
		var margin = {
			top: 20,
			right: 30,
			bottom: 30,
			left: 40
		},
		width = 825 - margin.left - margin.right,
		height = 450 - margin.top - margin.bottom;

		var paddingForText = 15;

		// Parse the date
		var parseDate = d3.timeParse("%d-%b-%y");

		// Set the ranges
		var x = d3.scaleTime().range([0, width]);
		var y = d3.scaleLinear().range([height, 0]);

		// Define the axes
		var xAxis = d3.axisBottom(x).ticks(3);

		var yAxis = d3.axisLeft(y).ticks(10);

		// Define the line
		var valueline = d3.line()
			.x(function(d) {
				return x(d.date);
			})
			.y(function(d) {
				return y(d.bitcoin_dominance);
			});

		// Adds the svg canvas
		var svg = d3.select("#priceWithMilestones")
			.append("svg")
			.style("background-color", "#ffffff")
			//.attr("width", width + margin.left + margin.right)
			//.attr("height", height + margin.top + margin.bottom)
			.attr("preserveAspectRatio", "xMinYMin meet")
			.attr("viewBox", "0 0 825 450")
			.attr("id", "priceWithEverything")
			.append("g")
			.attr("transform",
				"translate(" + margin.left + "," + margin.top + ")");
				
		var aspect = width / height,
			chart = d3.select('#priceWithMilestones');
		d3.select(window)
		  .on("resize", function() {
			var targetWidth = chart.node().getBoundingClientRect().width;
			chart.attr("width", targetWidth);
			chart.attr("height", targetWidth / aspect);
		  });

		data = tokenPricesArray;
		
		tokenPricesArray.sort(function(a,b){
			var c = new Date(a.date);
			var d = new Date(b.date);
			return c-d;
		});
		
		// Get the data
		data.forEach(function(d) {
			d.date = parseDate(d.date);
			d.bitcoin_dominance = +d.bitcoin_dominance;
		});

		// Scale the range of the data
		x.domain(d3.extent(data, function(d) {
			return d.date;
		}));
		y.domain([0, 100]);

		// Add the valueline path.
		svg.append("path")
			.data([data])
			.attr("class", "line")
			.attr("stroke", "steelblue")
			.attr("fill", "none")
			.attr("d", valueline);

		svg.append("g").selectAll("circle")
			.data(data.filter(function(d){return d.notes}))
			.enter()
			.append("circle")
			.attr("r", 4)
			.attr("cx", function(d) {
				return x(d.date)
			})
			.attr("cy", function(d) {
				return y(d.bitcoin_dominance)
			})
			.classed("milestone-circle", true)
			.attr("fill", "none")
			//.attr("stroke", "#BA85FF")
			.attr("stroke", "#000000");

		svg.append("g").selectAll("text")
			.data(data)
			.enter()
			.append("text")
			.attr("x", function(d) {
				return x(d.date) - paddingForText
			})
			.attr("y", function(d) {
				return y(d.bitcoin_dominance) + paddingForText
			})
			//.attr("fill", "white")
			// .text(function(d) {
				// return d.notes
			// })
			// .classed("milestone-circle", true)
			// .style("font-family", "Roboto")
			// .style("font-size", "14px")
			;

		// Add the X Axis
		svg.append("g")
			.attr("class", "xaxis")
			.attr("transform", "translate(0," + height + ")")
			.call(xAxis);

		// Add the Y Axis
		svg.append("g")
			.attr("class", "yaxis")
			.call(yAxis);
body {font-family: Roboto;}
#priceWithMilestones {position: relative;}
.title {position: absolute; top: 0; text-align: center; width: 100%; }
.legend {position: absolute; top: 400px; right: 0; }
<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<div id="priceWithMilestones">
<div class="title"><h1>Marketcap Dominance</h1></div>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

</script>
...