gpt4 book ai didi

javascript - D3 折线图没有使用标签正确绘制 X 和 Y 轴

转载 作者:太空宇宙 更新时间:2023-11-04 16:19:42 26 4
gpt4 key购买 nike

在下面的折线图中,虽然图表绘制正确,但带标签的 x 轴和 y 轴绘制不正确。有人可以帮我解决这个问题吗?

片段:

<html>

<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>

</head>

<body ng-app="myApp" ng-controller="myCtrl">

<svg width="500" height="300"></svg>

<script>
//module declaration
var app = angular.module('myApp',[]);

//Controller declaration
app.controller('myCtrl', function($scope){

var data = [
{x: "2016-01-10", y: "10.02"},
{x: "2016-02-10", y: "15.02"},
{x: "2016-03-10", y: "50.02"},
{x: "2016-04-10", y: "40.02"},
{x: "2016-05-10", y: "10.02"}
];

var parseTime = d3.timeParse("%Y-%m-%d");

var xScale = d3.scaleTime().range([0,500]).domain(d3.extent(data, function(d){ return parseTime(d.x)}));

var yScale = d3.scaleLinear().range([300,0]).domain([0,50]);


//Plotting domain on x and y axis
var xAxis = d3.scaleBand().rangeRound([0, 500]).padding(0.6);
var yAxis = d3.scaleLinear().rangeRound([300, 0]);
xAxis.domain(data.map(function(d) { return d.letter; }));
yAxis.domain([0, d3.max(data, function(d) { return d.frequency; })]);

//Final printing of elements on svg

//Plortting of x-axis
d3.select("svg")
.append("g")
.attr("transform", "translate(0," + 300 + ")")
.call(d3.axisBottom(xAxis));

//Plotting of y-axis
d3.select("svg")
.append("g")
.call(d3.axisLeft(yAxis).ticks(10, "%"));


//the line function for path
var lineFunction = d3.line()
.x(function(d) {return xScale(parseTime(d.x)); })
.y(function(d) { return yScale(d.y); })
.curve(d3.curveLinear);

//Main svg container
var mySVG = d3.select("svg");

//defining the lines
var path = mySVG.append("path");

//plotting lines
path
.attr("d", lineFunction(data))
.attr("stroke",function() { return "hsl(" + Math.random() * 360 + ",100%,50%)"; })
.attr("stroke-width", 2)
.attr("fill", "none");

});
</script>

</body>

</html>

结果:

enter image description here

问题:

  1. The X-Axis is not coming
  2. Labels on X-Axis missing
  3. Lables on Y-Axis missing

请帮助我正确获取图表。

最佳答案

关于 y 轴:您没有从原点位置平移它。应该是:

 d3.select("svg")
.append("g")
.attr("transform", "translate(30, 0)")//30 here is just an example
.call(d3.axisLeft(yAxis).ticks(10, "%"));

关于 x 轴:您将其一直平移到高度。它应该小于:

  d3.select("svg")
.append("g")
.attr("transform", "translate(0," + (height - 30) + ")")//30 is just an example
.call(d3.axisBottom(xAxis));

简而言之:正确设置边距并根据这些边距平移轴。

PS:刻度中不会显示任何内容,因为您的数据中没有字母频率

关于javascript - D3 折线图没有使用标签正确绘制 X 和 Y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757361/

26 4 0