D3简单条形图未更新

时间:2016-08-08 14:48:19

标签: javascript d3.js svg

我已经创建了D3条形图,但我不确定如何更新它。数据本身正在更新,但是当我尝试浏览.enter().exit()内容时,我最常遇到的错误是.exit()函数不存在。我的观点是,我不确定更新我的图表的正确方法。

我提供了codepen here,但所有相关代码都在下面。

var b_margin = {top: 20, right: 20, bottom: 30, left: 100},
        b_width = 450 - b_margin.left - b_margin.right,
        b_height = 200 - b_margin.top - b_margin.bottom;

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, b_width], .1);

    var y = d3.scale.linear()
        .range([b_height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

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

    var barsvg = d3.select("body").append("svg")
        .attr("width", b_width + b_margin.left + b_margin.right)
        .attr("height", b_height + b_margin.top + b_margin.bottom)
      .append("g")
        .attr("transform", "translate(" + b_margin.left + "," + b_margin.top + ")");

createBarChart = function()
{
  x.domain(bardata.map(function(d) { return d.age; }));
  y.domain([0, d3.max(bardata, function(d) { return d.population; })]);

  barsvg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + b_height + ")")
      .call(xAxis);

  barsvg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Frequency");

  barsvg.selectAll(".bar")
      .data(bardata)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.age) + 25; })
      .attr("width", x.rangeBand() - 50)
      .attr("y", function(d) { return y(d.population); })
      .attr("height", function(d) { return b_height - y(d.population); });

  function type(d) {
    d.population = +d.population;
    return d;
  }
}

updateBarChart = function()
{
  // Bar chart svg update
  bardata = [
    {age: "title1", population: 50},
    {age: "title2", population: 25},
    {age: "title3", population: 70}
  ]

  barsvg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + b_height + ")")
      .call(xAxis);

  barsvg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Frequency");

  barsvg.selectAll(".bar")
      .data(bardata)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.age) + 25; })
      .attr("width", x.rangeBand() - 50)
      .attr("y", function(d) { return y(d.population); })
      .attr("height", function(d) { return b_height - y(d.population); });

  barsvg.exit().remove();

  barsvg.attr("y", function(d) { return y(d.value); })
        .attr("height", function(d) { return height - y(d.value); });
}

编辑:我的updateBarData函数如下所示:

2 个答案:

答案 0 :(得分:1)

很棒的教程here

理念是,首先创建一个空选择并将数据绑定到它。

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'realm-android'
apply plugin: 'com.neenbedankt.android-apt'


android {
    compileSdkVersion 24
    buildToolsVersion "24"
//    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.gogetapps.uternity"
        minSdkVersion 18
        targetSdkVersion 24
        versionCode 5
        versionName "0.1"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }

    configurations {
        all*.exclude group: 'org.apache.httpcomponents'
        all*.exclude group: 'org.apache.commons'
        all*.exclude group: 'org.apache.commons'
    }
}

repositories {
    maven { url "https://jitpack.io" }
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    testCompile 'junit:junit:4.12'
    apt 'com.jakewharton:butterknife-compiler:8.0.1'
    compile('com.google.android.gms:play-services:9.0.2') {
        exclude group: 'com.google.guava'
    }
    compile 'dev.dworks.libs:volleyplus:+'
    compile project(':cmediaplayer')
    compile 'com.jakewharton:butterknife:8.0.1'
    compile 'com.android.support:percent:24.0.0'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
    compile ('com.android.support:support-v4:24.0.0') {
        force = true
    }
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.github.jkwiecien:EasyImage:1.2.3'
    compile 'com.mukesh:countrypicker:1.1.3'
    compile 'com.sa90.materialarcmenu:library:1.4.1'
    compile 'se.emilsjolander:stickylistheaders:2.7.0'
    compile 'com.makeramen:roundedimageview:2.2.1'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile('commons-validator:commons-validator:1.4.1') {
        exclude group: 'commons-logging'
    }
    compile('commons-io:commons-io:2.5') {
        exclude group: 'commons-logging'
    }
    compile('commons-lang:commons-lang:2.2') {
            exclude group: 'commons-logging'
    }
    compile 'com.timehop.stickyheadersrecyclerview:library:0.4.3'
    compile 'com.github.curioustechizen.android-ago:library:1.3.2'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'net.alhazmy13.MediaPicker:libary:2.1.4'
    compile 'com.baoyz.swipemenulistview:library:1.3.0'
    compile 'com.nononsenseapps:filepicker:2.5.3'
    compile 'com.writingminds:FFmpegAndroid:0.3.2'
    compile 'com.kbeanie:image-chooser-library:1.5.8@aar'
    compile 'me.zhanghai.android.materialprogressbar:library:1.1.7'
    compile 'com.github.deano2390:MaterialShowcaseView:1.1.0'
    compile 'com.github.barteksc:android-pdf-viewer:1.4.0'
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.+'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.1@aar') {
        transitive = true;
    }

}

现在,我们需要根据附加的数据创建元素。

var bars = barsvg.selectAll(".bar")
.data(bardata)  // bars is empty but data is binded to it

要删除旧元素,我们使用退出选择

var newBars = bars.enter();  // creates new elements
newBars.apped("rect").........  // we do all the manipulation here

希望这会有所帮助。



var obsoletebars = bars.exit(); //contains excess bars
obsoletebars.remove(); // removes them

		var b_margin = {top: 20, right: 20, bottom: 30, left: 100},
    b_width = 450 - b_margin.left - b_margin.right,
    b_height = 200 - b_margin.top - b_margin.bottom;

var x = d3.scale.ordinal()
.rangeRoundBands([0, b_width], .1);

var y = d3.scale.linear()
.range([b_height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

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

var barsvg = d3.select("body").append("svg")
.attr("width", b_width + b_margin.left + b_margin.right)
.attr("height", b_height + b_margin.top + b_margin.bottom)
.append("g")
.attr("transform", "translate(" + b_margin.left + "," + b_margin.top + ")");

var bardata = [
  { age: "Public", population: 50 },
  { age: "Private, for-profit", population: 100 },
  { age: "Nonprofit", population: 25 }
];

createBarChart();

$('#btn').click(function() {
  updateBarChart();
});

function createBarChart()
{
  x.domain(bardata.map(function(d) { return d.age; }));
  y.domain([0, d3.max(bardata, function(d) { return d.population; })]);

  barsvg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + b_height + ")")
    .call(xAxis);

  barsvg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Frequency");

  barsvg.selectAll(".bar")
    .data(bardata)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return x(d.age) + 25; })
    .attr("width", x.rangeBand() - 50)
    .attr("y", function(d) { return y(d.population); })
    .attr("height", function(d) { return b_height - y(d.population); });

  function type(d) {
    d.population = +d.population;
    return d;
  }
}

function updateBarChart()
{
	
var random = function() { return Math.floor(Math.random() * 70) + 30 };	
  // Bar chart svg update
  bardata = [
  { age: "Public", population: random() },
  { age: "Private, for-profit", population: random() },
  { age: "Nonprofit", population: random() }
];

  barsvg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + b_height + ")")
    .call(xAxis);

  barsvg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Frequency");

  var bars = barsvg.selectAll(".bar")
    .data(bardata);
	
    bars.enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return x(d.age) + 25; })
    .attr("width", x.rangeBand() - 50)
    .attr("y", function(d) { return y(d.population); })
    .attr("height", function(d) { return b_height - y(d.population); });

  bars.exit().remove();	
	
  bars.attr("y", function(d) { 
	  return y(d.population); })
    .attr("height", function(d) { return b_height - y(d.population); });
}

#btn {
  border: 2px solid #212121;
  width: 150px;
  text-align: center;
  padding: 15px;
  cursor: pointer;
}




答案 1 :(得分:1)

D3并不需要重写新栏。只需在更新时执行以下操作:



*/10 * * * * php myscript.php
@reboot /bin/sleep 60; php myscript.php