_.each(items, function(city){
   var comma = d3.format(',');
   city.set({
     poblacion  : comma(city.get('poblacion')),
     autos_2013 : comma(city.get('autos_2013'))
   });
   this.$('thead').append(this.worst_city(city.attributes));
 }, this);
    var format = function (value) {
      var formatter = d3.format('0,000');

      if (_.isNumber(value)) {
        return formatter(value.toFixed(2));
      }
      return 0;
    };
 .group((d) => {
   let monthStr = null;
   if (d.publishDate !== null) { // ignore undateable ones
     const format = d3.format('02d');
     monthStr = `${d.publishDate.getFullYear()}/${format((d.publishDate.getMonth() + 1))}`;
   }
   return monthStr;
 })
Example #4
0
 .text(function(dd) {
   // return total amout
   if (chart.questionBreakdownValues[d.group].questionValuesP[dd] > 0) {
     return "(" + d3.format('0%')(chart.questionBreakdownValues[d.group].questionValuesP[dd]) + ")";
   } else {
     return '';
   }
 })
Example #5
0
piper.axisYFormatSI = function(_config) {
    var config = {
        axisY: null
    };
    piper.utils.override(config, _config);
    config.axisY.tickFormat(d3.format(".2s"));
    return {};
};
Example #6
0
  formatSensorValue(aspect, value) {
    if(value == null) return undefined;
    switch(aspect) {
    case 'temperatureSensor':
      let temp = value;
      if(this.get('temperatureUnits') === 'f')
        temp = util.tempToFahrenheit(temp);
      return d3.format(`.${this.get('temperaturePrecision')}f`)(temp) + '°';
      break;

    case 'humiditySensor':
      return d3.format(`.${this.get('humidityPrecision')}f`)(value) + '%';
      
    default:
      return value;
    }
  }
Example #7
0
  axis: computed('scale', 'orient', 'tickCount', 'tickSize', 'tickFormat', 'tickPadding', function () {
    var props = this.getProperties('scale', 'orient', 'tickSize', 'tickFormat', 'tickPadding', 'ticks');

    if (typeof props.tickFormat === 'string') {
      props.tickFormat = d3.format(props.tickFormat);
    }

    return props.scale && assign(d3.svg.axis(), props);
  }).readOnly(),
 axis: computed(() => ({
   x: {
     type: 'timeseries',
     tick: { format: '%b %e' },
   },
   y: {
     tick: { format: d3format('d'), count: 6 }
   }
 })),
Example #9
0
export function d3format(format, number) {
  const formatters = {};
  // Formats a number and memoizes formatters to be reused
  format = format || '.3s';
  if (!(format in formatters)) {
    formatters[format] = d3.format(format);
  }
  return formatters[format](number);
}
Example #10
0
 var d3format = function(d) {
     switch (type) {
         case "s":
             var prefix = d3.formatPrefix(d);
             return prefix.scale(d).toFixed() + prefix.symbol;
         default:
             return d3.format("." + precision + type)(d);
     }
 };
Example #11
0
function getEndText(ax, end) {
    var initialVal = ax.range[end],
        diff = Math.abs(initialVal - ax.range[1 - end]),
        dig;

    if(ax.type === 'date') {
        return Lib.ms2DateTime(initialVal, diff);
    }
    else if(ax.type === 'log') {
        dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
        return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
    }
    else { // linear numeric (or category... but just show numbers here)
        dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
            Math.floor(Math.log(diff) / Math.LN10) + 4;
        return d3.format('.' + String(dig) + 'g')(initialVal);
    }
}
Example #12
0
        formatDimension: function (dimension, key, agg) {
            var _this = this;

            switch(dimension.type){
                case 'date':
                    var format = _this.aggFormat(agg);
                    return d3.time.format(format)(new Date(parseInt(key)));

                case 'number':
                    if (dimension.format === '$') {
                        return '$' + d3.format(',.2f')(key);
                    }
                    return dimension.format ? d3.format(format)(key) : key;

                default:
                    return dimension.format ? d3.format(format)(key) : key;
            }
        },
        scope.$watch('value', function(newVal) {
          if (!newVal)  {
            return;
          }
          var data = (scope.parseFn && scope.parseFn(newVal)) || _.identity(newVal);

          var chart = nv.models.lineChart().width(dim.width).height(dim.height);


          chart.useVoronoi(true);

          if (attrs.showLegend && attrs.showLegend === 'false') {
            chart.showLegend(false);
          }

          svg.datum(data).call(chart);

          var hasLabels = _.every(data, function(x) {
            return !_.isUndefined(x.labels);
          });

          if (hasLabels) {
            chart.xAxis.tickFormat(function(i) {
              if (i % 1 === 0) {
                return data[0].labels[i];
              } else {
                return '';
              }
            });
          } else {
            var y = d3.scale.linear().domain(chart.yAxis.scale().domain());
            chart.yAxis.tickValues(y.ticks(6));
            chart.yAxis.tickFormat(d3.format(',.3g'));

            var x = d3.scale.linear().domain(chart.xAxis.scale().domain());
            chart.xAxis.tickFormat(d3.format(',.3g'));
            chart.xAxis.tickValues(x.ticks(4));
          }

          chart.update();

        });
Example #14
0
  function tooltipHtml(d) {
    var winner = b3.getWinner(d);

    if(winner.name === undefined) {
      return '<span class="winner-name">Vacant Seat</span>';
    }

    return '<span class="winner-name">' + winner.name + '</span>' + 
           '<span style="color:' + b3.partyScale(winner.party) + '">' + winner.party + '</span> ' +
           '<span class="votes">' + d3.format(",")(winner.voteCount) + ' votes</span>';
  }
 serializeData() {
   const state = this.model.get('state');
   const params = this.model.get('parameters');
   const data = {};
   if(state.temperature != null) {
     var temp = state.temperature;
     if(params.temperatureUnits === 'f') temp = util.tempToFahrenheit(temp);
     data.temperature = d3.format(`.${params.temperaturePrecision}f`)(temp);
   }
   if(state.humidity != null) {
     data.humidity = d3.format(`.${params.humidityPrecision}f`)(
       state.humidity);
   }
   if(state.condition != null) {
     data.conditionIcon = util.weatherConditionToIcon(state.condition,
                                                     state.daytime);
     data.conditionName = util.weatherConditionToName(state.condition);
   }
   return data;
 }
Example #16
0
    update_axis : function(svg, scales){
      var x_axis = d3.svg.axis().scale(scales[0]).orient("bottom").tickFormat(d3.format("")),
          y_axis = d3.svg.axis().scale(scales[1]).orient("left");

      svg.select(".x_axis")
        .transition().duration(1500).ease("sin-in-out")
        .call(x_axis); 
      svg.select(".y_axis")
        .transition().duration(1500).ease("sin-in-out")
        .call(y_axis); 
    },
Example #17
0
function getEndText(ax, end) {
    var initialVal = ax.range[end],
        diff = Math.abs(initialVal - ax.range[1 - end]),
        dig;

    // TODO: this should basically be ax.r2d but we're doing extra
    // rounding here... can we clean up at all?
    if(ax.type === 'date') {
        return initialVal;
    }
    else if(ax.type === 'log') {
        dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
        return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
    }
    else { // linear numeric (or category... but just show numbers here)
        dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
            Math.floor(Math.log(diff) / Math.LN10) + 4;
        return d3.format('.' + String(dig) + 'g')(initialVal);
    }
}
 variables: ['All', 'Goods', 'Rents', 'Other'].map(component => {
     return {
         name: component,
         column: 'index',
         reverse: true,
         params: {component},
         years: _.range(2008, 2014),
         format: d3.format('.1f'),
         stoplight: true
     };
 })
Example #19
0
 ).then(chart => {
   if (!chart.data) {
     return { data: [], options: null }
   }
   let newOptions = _.clone(chart.options)
     newOptions.selected_indicators = selectedIndicators
   if (chart.options && !chart.options.yFormat) {
     newOptions.yFormat = d3.format(chartDef.yFormat)
   }
   if (chart.options && !chart.options.xFormat) {
     newOptions.xFormat = d3.format(chartDef.xFormat)
   }
   if (chart.options && !chart.options.xDomain) {
     newOptions.xDomain = indicatorOrder
   }
   if (chartDef.palette) {
     newOptions.color = palettes[chartDef.palette]
   }
   newOptions.chartInDashboard = true
   return { data: chart.data, options: newOptions }
 })
Example #20
0
var init = function() {

    // partially define axes based on output size, not data domain
    x = d3.scale.linear()
        .range([0,util.width])
        .domain(d3.extent(data, _.property("adm"))).nice();

    y = d3.scale.linear()
        .range([util.height,0])
        .domain(d3.extent(data, _.property("total"))).nice();

    xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(d3.format("s"));

    yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    // create SVG
    exPercapita.svg = d3.select("#graphs").append("svg")
        .attr("id", "ex-percapita")
        .attr("width", util.width + util.margin.left + util.margin.right)
        .attr("height", util.height + util.margin.top + util.margin.bottom);

    graph = exPercapita.svg.append("g")
        .attr("transform", "translate(" + util.margin.left + "," + util.margin.top + ")");

    // navigation button
    d3.select("#nav").append("li")
        .text("Per-student Expenditure vs Enrollment")
        .classed("nav", true)
        .on("click", function() {
            util.showGraph(d3.select(d3.event.target), exPercapita.svg);
        });

    // capture zoom events
    graph.append("rect")
        .attr("class", "overlay")
        .attr("width", util.width)
        .attr("height", util.height);

    // create axis groups; don't draw tick marks yet
    util.xaxis("Number of Students")(graph);
    util.yaxis("Expenditure Per Student (USD)")(graph);

    dataPane = util.dataPane(graph);

    (d3.behavior.zoom().x(x).on("zoom", exPercapita.draw)).center([0,0]).scaleExtent([1,100])(exPercapita.svg);

    initialized = true;
};
Example #21
0
     ['Other', 'Other Costs']].map(component => {
     return {
         name: component[1],
         column: 'index',
         metric: nameToURL(component[0]),
         reverse: true,
         params: _getParams(component[0]),
         years: _.range(2008, 2014),
         format: d3.format('.1f'),
         stoplight: true
     };
 })
Example #22
0
	drawYieldDimCountChart() {

		let {yield_count_chart} = this.refs;
		let width = yield_count_chart.clientWidth,
			height = yield_count_chart.clientHeight;

		this.yieldChartW = width;
		this.yieldChartH = height;

		//收益率统计
		let yieldDimCountChart = /*this.yieldDimCountChart ||*/ DC.barChart(yield_count_chart);
		// yieldDimCountChart.filterAll();

		yieldDimCountChart
			.width(width)
			.height(height)
			.transitionDuration(transitionDuration)
			.margins({top:10, right:20, bottom:30, left:30})
			.dimension(this.yieldDim)
			.group(this.yieldGroup)
			.renderHorizontalGridLines(true)
			.colors(this._isLight ? '#4F4F4F' : '#aaa')
			// .excludedColor(this._isLight ? '' : '#555')
			.elasticY(true)
			//.centerBar(true)
			.gap(1)
			.drawOutline(true)
			// .mouseZoomable(true)
			// .zoomOutRestrict(false)
			// .zoomScale([1,4])
			// .controlsUseVisibility(true)
			// .turnOnControls(true)
			.x(d3.scale.linear().domain([0, barChartBars+1]));
			//.x(d3.scale.ordinal())
			//.xUnits(DC.units.ordinal);
			//.x(d3.scale.linear().domain([this.yield100Range[0], barChartBars+1]));

		let rangeInterval = (this.yield100Range[1] - this.yield100Range[0]) / barChartBars ,
		    minYield100 = this.yield100Range[0];

		yieldDimCountChart.xAxis().tickFormat((v) => {
			var yieldRate = v * rangeInterval + minYield100;
			return (yieldRate + '').slice(0, yieldRate>=0 ? 4 : 5) + '%'; 
		}).ticks(6).innerTickSize(5);
		// yieldDimCountChart.yAxis().tickFormat((v) => {return +v }).ticks(5).innerTickSize(5);
		yieldDimCountChart.yAxis().tickFormat(d3.format('d')).ticks(5).innerTickSize(5);
		//yieldDimCountChart.on('filtered', _.debounce(this.onChartFiltered.bind(this)));
		yieldDimCountChart.on('filtered', this.onChartFiltered.bind(this));
		//yieldDimCountChart.filterHandler(debounceFilter);

		window.yieldDimCountChart = yieldDimCountChart;
		this.yieldDimCountChart = yieldDimCountChart;
	}
Example #23
0
const renderProgressBar = (taskSummary) => {
  const { items, fixed, noterror } = taskSummary;

  const total = items;
  const completed = fixed + noterror;
  const progressStyle = {
    width: (completed / total) * 100 + '%'
  };

  return (
    <div className='col4'>
      <h4 className='block space-bottom0'>
        <strong>{d3.format(',')(completed)}</strong> complete
        <span className='quiet'> of {d3.format(',')(total)}</span>
      </h4>
      <div className='progress-bar clip contain fill-darken1 col12'>
        <div style={progressStyle} className='progress fill-darkgreen pin-left block col12'></div>
      </div>
    </div>
  );
};
    var update = function(data) {
      if (typeof data === 'undefined') {
        return;
      }

      chart = nv.models.scatterChart()
        .duration(300);

      chart.xAxis.tickFormat(function(d) { return d3.time.format('%m/%d %H:%M')(new Date(d)); });
      if (attrs.forceY) {
        chart.forceY(angular.fromJson(attrs.forceY));
      }
      if (attrs.tickFormatX) {
        chart.yAxis.tickFormat(d3.format(attrs.tickFormatX));
      }
      if (attrs.tickFormatY) {
        chart.yAxis.tickFormat(d3.format(attrs.tickFormatY));
      }

      svg.datum(data).call(chart);
    };
Example #25
0
  render: function() {
    var fmt = this.props.hasLoaded ? d3.format(',') : _.constant('-'),
        dfmt = this.props.hasLoaded ? d3.format('.4f') : _.constant('-'),
        {truePositives, falsePositives,
         falseNegatives, precision, recall, f1score} = this.props.stats;

    return (
      <div className="precision-recall">
        <table>
          <tbody>
            <tr>
              <th></th>
              <th>True</th>
              <th>False</th>
              <th>Precision</th>
              <th>Recall</th>
              <th>f1score</th>
            </tr>
            <tr>
              <th>Positive</th>
              <td>{fmt(truePositives || 0)}</td>
              <td>{fmt(falsePositives || 0)}</td>
              <td className="other-stats">{dfmt(precision || 0)}</td>
              <td className="other-stats">{dfmt(recall || 0)}</td>
              <td className="other-stats">{dfmt(f1score || 0)}</td>
            </tr>
            <tr>
              <th>Negative</th>
              <td className="na">-</td>
              <td>{fmt(falseNegatives || 0)}</td>
              <td className="other-stats"></td>
              <td className="other-stats"></td>
              <td className="other-stats"></td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
Example #26
0
const formatData = function(value, _prefix, _suffix, rounded, isMoney) {
    let prefix = defined(_prefix) ? _prefix : '';
    let suffix = defined(_suffix) ? _suffix : '';

    if(value === null){
      return 'no data';
    }

    if(suffix === 's'){
      return formatSeconds(value);
    }

    if(rounded){
      return prefix + parseInt(value, 10) + suffix;
    }

    if(value === 0){
      return prefix + 0 + suffix;
    }

    if (isMoney) {
      return prefix + d3.format('.2f')(value) + suffix;
    }

    if (value > 1000) {
      return prefix + d3.format('.2s')(value) + suffix;
    }

    if (isFloat(value)) {
        if (rounded === false) {
            return prefix + d3.format('.1f')(value) + suffix;
        } else {
            return prefix + d3.format('f')(value) + suffix;
        }
    }

    return prefix + value + suffix;
}
Example #27
0
 // Formats text for units display
 formatText(initialString, initialSize) {
     let string = initialString;
     let size = initialSize;
     while (size > 0) {
         string /= 100;
         size--;
     }
     while (size < 0) {
         string *= 100;
         size++;
     }
     const format = d3.format('.2f');
     return format(string);
 }
          nv.addGraph(function() {
            var chart = nv.models.multiBarChart().height(dim.height).width(dim.width);
            var data = rankGraphData(newVal);

            chart.yAxis.tickFormat(d3.format(',.3g'));
            chart.stacked(attrs.stacked);
            chart.reduceXTicks(false);
            chart.staggerLabels(true);

            svg.datum(data)
              .transition().duration(100).call(chart);

            nv.utils.windowResize(chart.update);
          });
Example #29
0
 function setupYAxis() {
   yScale = d3.scale.linear()
     .domain([0, d3.max(data, function(d) {
       return d.count;
     })])
     .range([height - axisLabelMargin - margin.top - margin.bottom, 0]);
   yAxis = d3.svg.axis()
     .ticks(5)
     .tickFormat(d3.format('s'))
     .innerTickSize(-width + axisLabelMargin + margin.left + margin.right)
     .outerTickSize(0)
     .scale(yScale)
     .orient('left');
 }
Example #30
0
MuPlot._draw_axis = function(el, scales){

    var width = el.offsetWidth;
    var height = el.offsetHeight;

    var xAxis = d3.svg.axis()
         .scale(scales.x)
         .orient("bottom")
         .ticks(5)
         .tickSize(-height + this.padding_top, 0, 0)
         .tickFormat(d3.format("d"))

    var yAxis = d3.svg.axis()
        .scale(scales.y)
        .orient("left")
        .ticks(10)
        .tickSize(-width+this.padding_left, 0, 0)

    var svg = d3.select(el).select('.d3_mu_axis')

    svg.append("g")
         .attr("class", "d3_mu_x_axis")
         .attr("transform", "translate(0," + (height -  this.padding_bottom) + ")")
         .call(xAxis)

    var axis_start = scales.x.range()[0];
    var axis_width = scales.x.range()[1]-scales.x.range()[0];
    svg.append("text")      // text label for the x axis
        .attr("x", axis_start + axis_width / 2 )
        .attr("y", height - this.padding_text )
        .style("text-anchor", "middle")
        .text("Sampling date");

    svg.append("g")
        .attr("class", "d3_mu_y_axis")
        .attr("transform", "translate(" + (this.padding_left) + ",0)")
        .call(yAxis);


    svg.append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", this.padding_text)
        .attr("x",  - (height - this.padding_bottom)/2)
        .attr("dy", "1em")
        .style("text-anchor", "middle")
        .text("Distance to root");

    this._draw_text(el, scales)
};