简体   繁体   中英

Changing size of ticks on y axis and adding legend in D3.js

I am new D3 and i am trying to draw multiple plots based on incoming data. Here i have tried plotting one of them and will add 4 more like these on the same page. Following is my code so far:

var data = [
{"mytime": "2015-12-01T11:10:00.000Z", "value": 64},
{"mytime": "2015-12-01T11:15:00.000Z", "value": 67},
{"mytime": "2015-12-01T11:20:00.000Z", "value": 70},
{"mytime": "2015-12-01T11:25:00.000Z", "value": 64},
{"mytime": "2015-12-01T11:30:00.000Z", "value": 72},
{"mytime": "2015-12-01T11:35:00.000Z", "value": 75},
{"mytime": "2015-12-01T11:40:00.000Z", "value": 71},
{"mytime": "2015-12-01T11:45:00.000Z", "value": 80}
];


var margin = { top: 30, right: 30, bottom: 40, left:50 };

var height = 200 - margin.top - margin.bottom,
    width = 800 - margin.left - margin.right;

console.log("1")
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
data.forEach(function(d) {
          d.mytime = parseDate(d.mytime);
        });

var x_extent = d3.extent(data, function(d){
    return d.mytime});
console.log("2")
var y_extent = d3.extent(data, function(d){
    return d.value});

var x_scale = d3.time.scale()
    .domain(x_extent)
    .range([0,width]);

console.log("3")

var y_scale = d3.scale.linear()
    .domain([0,y_extent[1]])
    .range([height,0]);



//Line
var lineGen = d3.svg.line()
    .x(function (d) {
        console.log(d.date)
        return x_scale(d.mytime);
    })
    .y(function (d) {
        return y_scale(d.value);
    });

var myChart = d3.select('body').append('svg')
                .style('background', '#E7E0CB')
                .attr('width', width + margin.left + margin.right)
                .attr('height', height + margin.top + margin.bottom)
                .append('g')
                .attr('transform', 'translate('+ margin.left +', '+ margin.top +')')
                .append('svg:path')
                .datum(data)
                .attr('class', 'line')
                .attr("d",lineGen)
                .attr("data-legend","pulse")
                .attr('stroke', 'green')
                .attr('stroke-width', 0.5)
                .attr('fill', 'none');





var vGuideScale = d3.scale.linear()
    .domain([0,y_extent[1]])
    .range([height, 0])

var vAxis = d3.svg.axis()
    .scale(vGuideScale)
    .orient('left')
//    .tickFormat("") //For removing values
    .ticks(5)
var vGuide = d3.select('svg').append('g')
    vAxis(vGuide)
    vGuide.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')')
    vGuide.selectAll('path')
        .style({ fill: 'none', stroke: "#000"})
    vGuide.selectAll('line')
        .style({ stroke: "#000"})

console.log("4")
d3.select('svg').append('g')
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y",6)
      .attr("x",-50)
      .attr("dy", ".51em")
      .attr("font-size", "10px")
      .style("text-anchor", "end")
      .attr("fill", "green")
      .text("Value");

console.log("5")
var hAxis = d3.svg.axis()
    .scale(x_scale)
    .orient('bottom')
    .ticks(d3.time.minute, 5);

var hGuide = d3.select('svg').append('g')
    hAxis(hGuide)
    hGuide.attr('transform', 'translate(' + margin.left + ', ' + (height + margin.top) + ')')
    hGuide.selectAll('path')
        .style({ fill: 'none', stroke: "#000"})
    hGuide.selectAll('line')
        .style({ stroke: "#000"})

I have few doubts regarding formatting of the code:

  1. How to add legend to the code when i tried the following link but i am getting error on using the call function http://bl.ocks.org/ZJONSSON/3918369
  2. How to reduce reduce tick size on y axis?

Thanks

The answer here is to use css to control the style of your components (including font sizes). For instance, for all fonts in your SVG tag:

svg {
  font: 10px sans-serif;
}  

Second, building a legend can be pretty simple:

var legend = myChart.append("g")
  .attr("class", "legend")
  .attr("transform", "translate(" + 5 + "," + (height - 25) + ")")

legend.append("rect")
  .style("fill", "green")
  .attr("width", 20)
  .attr("height", 20);

legend.append("text")
  .text("My Awesome Legend Item")
  .attr("x", 25)
  .attr("y", 12);

Full code sample:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> <style> svg { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } </style> </head> <body> <script> var data = [{ "mytime": "2015-12-01T11:10:00.000Z", "value": 64 }, { "mytime": "2015-12-01T11:15:00.000Z", "value": 67 }, { "mytime": "2015-12-01T11:20:00.000Z", "value": 70 }, { "mytime": "2015-12-01T11:25:00.000Z", "value": 64 }, { "mytime": "2015-12-01T11:30:00.000Z", "value": 72 }, { "mytime": "2015-12-01T11:35:00.000Z", "value": 75 }, { "mytime": "2015-12-01T11:40:00.000Z", "value": 71 }, { "mytime": "2015-12-01T11:45:00.000Z", "value": 80 }]; var margin = { top: 30, right: 30, bottom: 40, left: 50 }; var height = 200 - margin.top - margin.bottom, width = 800 - margin.left - margin.right; console.log("1") var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse; data.forEach(function(d) { d.mytime = parseDate(d.mytime); }); var x_extent = d3.extent(data, function(d) { return d.mytime }); console.log("2") var y_extent = d3.extent(data, function(d) { return d.value }); var x_scale = d3.time.scale() .domain(x_extent) .range([0, width]); console.log("3") var y_scale = d3.scale.linear() .domain([0, y_extent[1]]) .range([height, 0]); //Line var lineGen = d3.svg.line() .x(function(d) { console.log(d.date) return x_scale(d.mytime); }) .y(function(d) { return y_scale(d.value); }); var myChart = d3.select('body').append('svg') .style('background', '#E7E0CB') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')'); myChart .append('svg:path') .datum(data) .attr('class', 'line') .attr("d", lineGen) .attr("data-legend", "pulse") .attr('stroke', 'green') .attr('stroke-width', 0.5) .attr('fill', 'none'); var legend = myChart.append("g") .attr("class", "legend") .attr("transform", "translate(" + 5 + "," + (height - 25) + ")") legend.append("rect") .style("fill", "green") .attr("width", 20) .attr("height", 20); legend.append("text") .text("My Awesome Legend Item") .attr("x", 25) .attr("y", 12); var vGuideScale = d3.scale.linear() .domain([0, y_extent[1]]) .range([height, 0]) var vAxis = d3.svg.axis() .scale(vGuideScale) .orient('left') // .tickFormat("") //For removing values .ticks(5) var vGuide = d3.select('svg').append('g').attr("class", "y axis") vAxis(vGuide) vGuide.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')') console.log("4") d3.select('svg').append('g') .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("x", -50) .attr("dy", ".51em") .attr("font-size", "10px") .style("text-anchor", "end") .attr("fill", "green") .text("Value"); console.log("5") var hAxis = d3.svg.axis() .scale(x_scale) .orient('bottom') .ticks(d3.time.minute, 5); var hGuide = d3.select('svg').append('g').attr("class", "x axis") hAxis(hGuide) hGuide.attr('transform', 'translate(' + margin.left + ', ' + (height + margin.top) + ')') </script> </body> </html> 

You can control the length of the ticks via the tickSize setter Like this:

var axis = d3.svg.axis()
    .scale(scale)
    .orient("right")
    .ticks(2)
    .tickSize(10)
    .tickFormat(formatPercent);

and then:

svg.append("g")
    .attr("class", "y axis")
    .call(axis);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM