圆在D3 Django图表上未正确对齐

时间:2018-12-04 13:27:01

标签: javascript python django python-3.x d3.js

这是我为了实现我的可视化所做的尝试。

<!DOCTYPE html>
<meta charset="utf-8">

<style> /* set the CSS */

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}

</style>
<body>

<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
 var real = {{values.real0|safe}}, pred = {{values.got0|safe}};
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");

// set the ranges
var x = d3.scaleLinear()
    .range([0, width])
    .domain([0, Object.keys(real).length])

;
var y = d3.scaleLinear()
    .range([height, 0])
    .domain([0, 1]);

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

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").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 + ")");


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

  // Add the scatterplot
 var x_axis = d3.axisBottom(x)
  svg.selectAll("dot")
      .data(real)
    .enter().append("circle")
      .attr("r", 5)
      .attr("cx", function(x_axis,d) { return d; })
      .attr("cy", function( d) { return d; });
 
 svg.selectAll("dot")
      .data(pred)
    .enter().append("circle")
      .attr("r", 10)
      .attr("cx", function(x_axis,d) { return d; })
      .attr("cy", function( d) { return d; });

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

  // Add the Y Axis
  svg.append("g")
      .call(d3.axisLeft(y));

// });

</script>
</body>

以上是我使用的模板。样本CSV文件为:Sample Csv

产生值的函数在views.py中写为:

@csrf_exempt
def getter(request):
     df_real_pred = pd.read_csv(r"logging\real_predicted\test.csv", sep=',', index_col=0)
    print(df_real_pred.columns)

    data = {
        'values': df_real_pred.to_dict(orient='list')

    }
    return render(request, 'tt/get.html', data)

请告诉我我错过的东西,因为我的图表很奇怪:
output graph

请让我知道如何使其正确对齐。

已编辑:该模板是我在Django中的项目的服务器模板。

1 个答案:

答案 0 :(得分:1)

应用x轴和y轴(两次)

.attr("cx", function( d, i) { return x(i); })
.attr("cy", function( d) { return y(d); });