How to use d3 - 10 common examples

To help you get started, we’ve selected a few d3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OmicsDI / ddi-web-app / src / app / profile / counting-data-dashboard-profile / dashboard-claim-count-profile / dashboard-claim-count-profile.component.ts View on Github external
//
        // console.log(Array.from(annualDataExtends).length);
        // var minDate = new Date(d3.min(annualDataExtends, d => {
        //     return parseInt(d["year"]);
        // }), 0, 0);
        // var maxDate = new Date(d3.max(annualDataExtends, d => {
        //     return parseInt(d["year"]);
        // }), 0, 1);

        const x0 = d3.scaleTime().range([0, width - 30]);
        const y0 = d3.scaleLinear().range([height - heightOffset, 0]);
        const y1 = d3.scaleLinear().range([height - heightOffset, 0]);
        const xAxis = d3.axisBottom(x0).ticks(yearSet.size + 2);
        const yAxisLeft = d3.axisLeft(y0).ticks(2);
        const yAxisRight = d3.axisRight(y1).ticks(2);
        const yLine = d3.scaleLinear().range([15, 0]);
        const yNavLine = d3.axisBottom(yLine).ticks(0);


        const minpointer = processedData.get('minYear');
        // console.log(minpointer);
        const max_M_P = processedData.get('max_M_P');
        const max_G_T = processedData.get('max_G_T');
        console.log(max_G_T);
        console.log(max_M_P);
        // console.log(max);
        x0.domain([new Date(Number(minpointer) - 1, 0, 0), new Date()]);

        y0.domain([0, Number(max_G_T)]);
        y1.domain([0, Number(max_M_P)]);
github w3reality / three-laser-pointer / examples / demo-path / src / index.js View on Github external
const getDem = (contours, northWest, southEast, radius, cb) => {
        // console.log('getDem():', contours, northWest, southEast, radius);

        const colorRange = d3.scaleLinear()
            .domain([0, contours.length])
            .interpolate(d3.interpolateRgb)
            .range(["#231918", "#ed6356"]);

        const objs = [];
        const addSlice = (coords, iContour) => {
            let [lines, extrudeShade] = buildSliceGeometry(
                coords, iContour, colorRange(iContour),
                contours, northWest, southEast, radius);
            lines.forEach((line) => { objs.push(line); });
            objs.push(extrudeShade);
        };

        // iterate through elevations
        for (let iContour = 0; iContour < contours.length; iContour++) {
            let level = contours[iContour].geometry.geometry;
github Uninett / nav / htdocs / static / js / src / ipam / viz.js View on Github external
var margin = opts.margin;
    var padding = opts.padding;

    if (!(inData.length && inData[0].parts.length)) {
      console.log("No data to display");
      return;
    }
    // get bounds of mountElem to responsively set width
    // var bounds = d3.select(mountElem).node().getBoundingClientRect();

    // normalize data
    var data = normalizeData(inData, opts);

    // === Drawing settings
    // [width, 0] makes the normalization step easier/prettier
    var xScale = d3.scale.linear()
          .range([width, 0]);

    var yScale = d3.scale.ordinal()
          .rangeRoundBands([0, height], .1);

    // Adapt yScale to data dimensions to ensure consistent spacing
    yScale.domain(_.map(data, function(d) { return d.prefix; }));

    var colors = d3.scale.category20();

    var svg;
    if (d3.select(mountElem).select("svg").empty()) {
      // Mount main SVG element
      svg = d3.select(mountElem)
        .append("svg")
        .attr("preserveAspectRatio", "xMaxYMin meet")
github wq / wq.app / packages / chart / src / chart.js View on Github external
.init(function(datasets, opts) {
            var step = plot.xset()(datasets).length; // Number of x axis labels
            var slots = step * (datasets.length + 1); // ~How many boxes to fit
            var space = opts.gwidth / slots; // Space available for each box
            r = d3.min([(space * 0.8) / 2, 20]); // "radius" of box (use 80%)
            wr = r / 2; // "radius" of whiskers
            var width = (datasets.length - 1) * space;
            datasets.forEach(function(dataset, i) {
                offsets[plot.id()(dataset)] = i * space - width / 2;
            });
        })
        .render(function(dataset) {
github rrag / react-stockcharts / src / lib / scale / financeEODDiscontinuousScale.js View on Github external
return prev || curr;
						});
			return sm ? false : d.startOfWeek;
		} },  // 1-week
		{ step: 3525e6, f: function(d) {return d.startOfMonth; } },  // 1-month
		{ step: 7776e6, f: function(d) {return d.startOfQuarter; } },  // 3-month
		{ step: 31536e6, f: function(d) {return d.startOfYear; } },  // 1-year
		{ step: 91536e15, f: function(d) {return isDefined(dateAccessor(d)) && (d.startOfYear && dateAccessor(d).getFullYear() % 2 === 0); } }  // 2-year
	];
	var timeScaleStepsBisector = d3.bisector(function(d) { return d.step; }).left;
	var bisectByIndex = d3.bisector(function(d) { return indexAccessor(d); }).left;
	var tickFormat = [
		[d3.time.format("%Y"), function(d) { return d.startOfYear; }],
		[d3.time.format("%b %Y"), function(d) { return d.startOfQuarter; }],
		[d3.time.format("%b"), function(d) { return d.startOfMonth; }],
		[d3.time.format("%d %b"), function(d) { return d.startOfWeek; }],
		[d3.time.format("%a %d "), function(/* d */) { return true; }]
	];
	function formater(d) {
		var i = 0, format = tickFormat[i];
		while (!format[1](d)) format = tickFormat[++i];
		var tickDisplay = format[0](dateAccessor(d));
		// console.log(t;ickDisplay);
		return tickDisplay;
	}

	function scale(x) {
		return backingLinearScale(x);
	}
	scale.isPolyLinear = function() {
		return true;
	};
github OmicsDI / ddi-web-app / src / app / profile / counting-data-dashboard-profile / dashboard-citations-count-profile / dashboard-citations-count-profile.component.ts View on Github external
y0.domain([0, Number(max_G_T)]);
        y1.domain([0, Number(max_M_P)]);


        const valueline = d3.line()
            .x(d => {

                return x0(new Date(d['year'], 0, 0));
            })
            .y(d => {

                return y0(parseInt(d['value'], 10));
            });

        const valueline2 = d3.line()
            .x(d => {
                // console.log('Line:');
                // console.log(x0(new Date(d["year"], 0, 0)));
                return x0(new Date(d['year'], 0, 0));
            })
            .y(d => {
                // console.log(y1(parseInt(d["value"])));
                return y1(parseInt(d['value'], 10));
            });

        if (genomicsList) {
            svg.append('path')
                .style('stroke', 'steelblue')
                .attr('d', valueline(genomicsList))
                .style('fill', d => {
                    console.log(d);
github wangqianwen0418 / DNN-Genealogy / src / components / PerformanceCompare / BarChart.tsx View on Github external
compare.forEach((cp: any) => {
            console.log(cp)
            let svg = d3.select(`.CorpusCompare .tab${cp.idx}`).insert('svg')
                .attr('width', '100%')
                .attr('height', '100%')
                .style('margin-top', '20px')
                .append('g')

            let x = d3.scaleLinear().range([0, width]),
                y = d3.scaleBand().range([height, 0]),
                y_group = d3.scaleBand().padding(0.05)

            let g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + 0 + ')')
            //    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        
            let data = cp.performance,
                keys = cp.nns
            
            let min: number, max: number;
            min = Math.floor(Math.min.apply(null, data.reduce((prev: any, cur: any) => {
                return prev.concat(keys.map((k: string) => cur[k]))
            },                                                [])) * 0.9)
            max = Math.ceil(Math.max.apply(null, data.reduce((prev: any, cur: any) => {
                return prev.concat(keys.map((k: string) => cur[k]))
            },                                               [])) * 1.1)
            x.domain([min, max])
github john-guerra / navio / shipyard / src / components / playground / navio-container / Navio.js View on Github external
function updateScales(levelToUpdate) {
    console.log("Update scales");
    var before = performance.now();
    // yScales=[];
    var lastLevel = dataIs.length-1;

    console.log("Delete unnecessary scales")
    // Delete unnecessary scales
    yScales.splice(lastLevel+1, yScales.length);
    levelToUpdate = levelToUpdate!==undefined ? levelToUpdate : lastLevel;
    yScales[levelToUpdate] = d3.scaleBand()
      .range([y0, h-nn.margin - 30])
      .paddingInner(0.0)
      .paddingOuter(0);



    console.log("Compute representatives")
    var representatives = [];
    if (dataIs[levelToUpdate].length>h) {
      var itemsPerpixel = Math.max(Math.floor(dataIs[levelToUpdate].length / (h*2)), 1);
      console.log("itemsPerpixel", itemsPerpixel);
      dataIs[levelToUpdate].itemsPerpixel = itemsPerpixel;
      for (var i = 0; i< dataIs[levelToUpdate].length; i+=itemsPerpixel ) {
        representatives.push(dataIs[levelToUpdate][i]);
      }
    } else {
github tensorflow / playground / src / playground.ts View on Github external
let cy = nodeIndexScale(0) + RECT_SIZE / 2;
  node2coord[node.id] = {cx, cy};
  // Draw links.
  for (let i = 0; i < node.inputLinks.length; i++) {
    let link = node.inputLinks[i];
    drawLink(link, node2coord, network, container, i === 0, i,
        node.inputLinks.length);
  }
  // Adjust the height of the svg.
  svg.attr("height", maxY);

  // Adjust the height of the features column.
  let height = Math.max(
    getRelativeHeight(calloutThumb),
    getRelativeHeight(calloutWeights),
    getRelativeHeight(d3.select("#network"))
  );
  d3.select(".column.features").style("height", height + "px");
}
github bloomberg / bqplot / js / src / OHLC.ts View on Github external
// Determine offset to use for translation
        let y_index  = px.h;
        if(px.h === -1) {
            y_index = px.o;
        }
        // Update all of the marks
        this.d3el.selectAll(".stick")
            .style("fill", function(d, i) {
                return (d.y[px.o] > d.y[px.c]) ? down_color : up_color;
            })
            .attr("stroke-width", this.model.get("stroke_width"));
        if(x_scale.model.type === "ordinal") {
            // If we are out of range, we just set the mark in the final
            // bucket's range band. FIXME?
            const x_max = d3.max(this.parent.range("x"));
            this.d3el.selectAll(".stick").attr( "transform", function(d, i) {
                return "translate(" + ((x_scale.scale(that.model.mark_data[i][0]) !== undefined ?
                                        x_scale.scale(that.model.mark_data[i][0]) : x_max) +
                                        x_scale.scale.bandwidth()/2) + "," +
                                      (y_scale.scale(d.y[y_index]) + y_scale.offset) + ")";
            });
        } else {
            this.d3el.selectAll(".stick").attr( "transform", function(d, i) {
                 return "translate(" + (x_scale.scale(that.model.mark_data[i][0]) +
                                     x_scale.offset) + "," +
                                     (y_scale.scale(d.y[y_index]) +
                                     y_scale.offset) + ")";
             });
        }

        // Draw the mark paths