【问题标题】:Dynamic variable selection in r2d3r2d3中的动态变量选择
【发布时间】:2019-07-09 11:51:21
【问题描述】:

我正在尝试使用 d3 示例脚本并将其转换为使用 r2d3 的绘图函数。我可以使用 r2d3 的“选项”参数将字符串传递到 d3 脚本中,但我想不出一种传递表达式的方法(我认为,这对于使其成为通用绘图函数是必要的)。从这里的示例工作https://bl.ocks.org/john-guerra/17fe498351a3e70929e2e36d081e1067 我的 .js 脚本称为 scatter_matrix.js:

// !preview r2d3 data=small_cars, d3_version = "3", css = "scatter_matrix.css", options = list(exclude = "mpg")
// r2d3: https://rstudio.github.io/r2d3
//

var size = 200,
    padding = 20;

var x = d3.scale.linear()
    .range([padding / 2, size - padding / 2]);

var y = d3.scale.linear()
    .range([size - padding / 2, padding / 2]);

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

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

 var color = d3.scale.linear()
               .domain([9, 30])
               .range(["red", "green"]);  

// I might need to include more of the lines outside this functions, inside the function?
r2d3.onRender(function(data, svg, width, height, options, error) {
  if (error) throw error;

  var domainByTrait = {},
      traits = d3.keys(data[0]).filter(function(d) { return d !== options.exclude; }),
      n = traits.length;

  traits.forEach(function(trait) {
    domainByTrait[trait] = d3.extent(data, function(d) { return d[trait]; });

});

  xAxis.tickSize(size * n);
  yAxis.tickSize(-size * n);

  var brush = d3.svg.brush()
      .x(x)
      .y(y)
      .on("brushstart", brushstart)
      .on("brush", brushmove)
      .on("brushend", brushend);

  svg.selectAll(".x.axis")
      .data(traits)
    .enter().append("g")
      .attr("class", "x axis")
      .attr("transform", function(d, i) { return "translate(" + (n - i - 1) * size + ",0)"; })
      .each(function(d) { x.domain(domainByTrait[d]); d3.select(this).call(xAxis); });

  svg.selectAll(".y.axis")
      .data(traits)
    .enter().append("g")
      .attr("class", "y axis")
      .attr("transform", function(d, i) { return "translate(0," + i * size + ")"; })
      .each(function(d) { y.domain(domainByTrait[d]); d3.select(this).call(yAxis); });

  var cell = svg.selectAll(".cell")
      .data(cross(traits, traits))
    .enter().append("g")
      .attr("class", "cell")
      .attr("transform", function(d) { return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")"; })
      .each(plot);

  // Titles for the diagonal.
  cell.filter(function(d) { return d.i === d.j; }).append("text")
      .attr("x", padding)
      .attr("y", padding)
      .attr("dy", ".71em")
      .text(function(d) { return d.x; });

  cell.call(brush);

  function plot(p) {
    var cell = d3.select(this);

    x.domain(domainByTrait[p.x]);
    y.domain(domainByTrait[p.y]);

    cell.append("rect")
        .attr("class", "frame")
        .attr("x", padding / 2)
        .attr("y", padding / 2)
        .attr("width", size - padding)
        .attr("height", size - padding);

    cell.selectAll("circle")
        .data(data)
      .enter().append("circle")
        .attr("cx", function(d) { return x(d[p.x]); })
        .attr("cy", function(d) { return y(d[p.y]); })
        .attr("r", 4)
        .style("opacity", 0.5)
        .style("fill", function(d) { return color(d.mpg); });
  }

  var brushCell;

  // Clear the previously-active brush, if any.
  function brushstart(p) {
    if (brushCell !== this) {
      d3.select(brushCell).call(brush.clear());
      x.domain(domainByTrait[p.x]);
      y.domain(domainByTrait[p.y]);
      brushCell = this;
    }
  }

  // Highlight the selected circles.
  function brushmove(p) {
    var e = brush.extent();
    svg.selectAll("circle").classed("hidden", function(d) {
      return e[0][0] > d[p.x] || d[p.x] > e[1][0]
          || e[0][1] > d[p.y] || d[p.y] > e[1][1];
    });
  }

  // If the brush is empty, select all circles.
  function brushend() {
    if (brush.empty()) svg.selectAll(".hidden").classed("hidden", false);
  }
});

function cross(a, b) {
  var c = [], n = a.length, m = b.length, i, j;
  for (i = -1; ++i < n;) for (j = -1; ++j < m;) c.push({x: a[i], i: i, y: b[j], j: j});
  return c;
}

而 scatter_matrix.css 是:

svg {
  font: 10px sans-serif;
  padding: 10px;
}

.axis,
.frame {
  shape-rendering: crispEdges;
}

.axis line {
  stroke: #ddd;
}

.axis path {
  display: none;
}

.cell text {
  font-weight: bold;
  text-transform: capitalize;
}

.frame {
  fill: none;
  stroke: #aaa;
}

circle {
  fill-opacity: .125;
}

circle.hidden {
  fill: #ccc !important;
}

.extent {
  fill: #000;
  fill-opacity: .125;
  stroke: #fff;
}

所以,如你所见,我变了

var domainByTrait = {},
      traits = d3.keys(data[0]).filter(function(d) { return d !== "species"; }),
      n = traits.length;

var domainByTrait = {},
          traits = d3.keys(data[0]).filter(function(d) { return d !== options.exclude; }),
          n = traits.length;

// !preview r2d3 data=small_cars, d3_version = "3", css = "scatter_matrix.css", options = list(exclude = "mpg")

然后可以选择要从图中排除的变量。但是,下面有

   cell.selectAll("circle")
            .data(data)
          .enter().append("circle")
            .attr("cx", function(d) { return x(d[p.x]); })
            .attr("cy", function(d) { return y(d[p.y]); })
            .attr("r", 4)
            .style("opacity", 0.5)
            .style("fill", function(d) { return color(d.mpg); });
      }

这是硬编码到脚本中的。我尝试使用

 options = list(exclude = "mpg", col = expr(d.mpg))

然后有

.style("fill", function(d) { return color(options.col); });
          }

但这没有用。我习惯在 R 中使用 quasiquotation 来解决这类问题,但我不确定在 JS 中是否有办法做到这一点? d3 很了不起,但是能够将脚本打包成函数就太棒了。

要重现这个情节,你应该只需要

small_cars <- mtcars %>% select(1:5)
r2d3::r2d3("catter_matrix.js", data=small_cars, d3_version = "3", css = "scatter_matrix.css", options = list(exclude = "mpg"))

【问题讨论】:

    标签: r d3.js r2d3


    【解决方案1】:

    实际上,我想我已经想通了。您可以使用 javascript 的 eval() 函数将字符串解析为代码。所以,如果我将 scatter_matrix.js 更改为

    // !preview r2d3 data= small_cars,  d3_version = "3", css = "T:/R Code Library/r2d3_library/scatter_matrix.css", options = list(exclude = "mpg", col = "d.mpg", col_range = "[10, 35]")
    // r2d3: https://rstudio.github.io/r2d3
    // n.b small_cars <- mtcars %>% select(1:5)
    
    function range(numbers) {
        numbers.sort();
        return [numbers[0], numbers[numbers.length - 1]];
    }
    
    var size = 200,
        padding = 20;
    
    var x = d3.scale.linear()
        .range([padding / 2, size - padding / 2]);
    
    var y = d3.scale.linear()
        .range([size - padding / 2, padding / 2]);
    
    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(6);
    
     var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(6);
    
     var color = d3.scale.linear()
                   .domain(eval(options.col_range))
                   .range(["red", "green"]);  
    
    // I might need to include more of the lines outside this functions, inside the function?
    r2d3.onRender(function(data, svg, width, height, options, error) {
      if (error) throw error;
    
      var domainByTrait = {},
          traits = d3.keys(data[0]).filter(function(d) { return d !== options.exclude; }),
          n = traits.length;
    
      traits.forEach(function(trait) {
        domainByTrait[trait] = d3.extent(data, function(d) { return d[trait]; });
    
    });
    
      xAxis.tickSize(size * n);
      yAxis.tickSize(-size * n);
    
      var brush = d3.svg.brush()
          .x(x)
          .y(y)
          .on("brushstart", brushstart)
          .on("brush", brushmove)
          .on("brushend", brushend);
    
      svg.selectAll(".x.axis")
          .data(traits)
        .enter().append("g")
          .attr("class", "x axis")
          .attr("transform", function(d, i) { return "translate(" + (n - i - 1) * size + ",0)"; })
          .each(function(d) { x.domain(domainByTrait[d]); d3.select(this).call(xAxis); });
    
      svg.selectAll(".y.axis")
          .data(traits)
        .enter().append("g")
          .attr("class", "y axis")
          .attr("transform", function(d, i) { return "translate(0," + i * size + ")"; })
          .each(function(d) { y.domain(domainByTrait[d]); d3.select(this).call(yAxis); });
    
      var cell = svg.selectAll(".cell")
          .data(cross(traits, traits))
        .enter().append("g")
          .attr("class", "cell")
          .attr("transform", function(d) { return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")"; })
          .each(plot);
    
      // Titles for the diagonal.
      cell.filter(function(d) { return d.i === d.j; }).append("text")
          .attr("x", padding)
          .attr("y", padding)
          .attr("dy", ".71em")
          .text(function(d) { return d.x; });
    
      cell.call(brush);
    
      function plot(p) {
        var cell = d3.select(this);
    
        x.domain(domainByTrait[p.x]);
        y.domain(domainByTrait[p.y]);
    
        cell.append("rect")
            .attr("class", "frame")
            .attr("x", padding / 2)
            .attr("y", padding / 2)
            .attr("width", size - padding)
            .attr("height", size - padding);
    
        cell.selectAll("circle")
            .data(data)
          .enter().append("circle")
            .attr("cx", function(d) { return x(d[p.x]); })
            .attr("cy", function(d) { return y(d[p.y]); })
            .attr("r", 4)
            .style("opacity", 0.5)
            .style("fill", function(d) { return color(eval(options.col)); });
      }
    
      var brushCell;
    
      // Clear the previously-active brush, if any.
      function brushstart(p) {
        if (brushCell !== this) {
          d3.select(brushCell).call(brush.clear());
          x.domain(domainByTrait[p.x]);
          y.domain(domainByTrait[p.y]);
          brushCell = this;
        }
      }
    
      // Highlight the selected circles.
      function brushmove(p) {
        var e = brush.extent();
        svg.selectAll("circle").classed("hidden", function(d) {
          return e[0][0] > d[p.x] || d[p.x] > e[1][0]
              || e[0][1] > d[p.y] || d[p.y] > e[1][1];
        });
      }
    
      // If the brush is empty, select all circles.
      function brushend() {
        if (brush.empty()) svg.selectAll(".hidden").classed("hidden", false);
      }
    });
    
    function cross(a, b) {
      var c = [], n = a.length, m = b.length, i, j;
      for (i = -1; ++i < n;) for (j = -1; ++j < m;) c.push({x: a[i], i: i, y: b[j], j: j});
      return c;
    }
    

    所以,基本上只是将eval(options.col) 换成d.mpg,然后将col = "d.mpg" 添加到r2d3 选项列表中。我还意识到颜色的范围是硬编码的,所以将eval(options.col_range) 换成[9,30],并在 r2d3 选项列表中添加了一个 col_range 元素。完成后,您可以在 R 中编写一个函数,例如

     plot_d3sc <- function(df, var) {
    
        col <- paste0("d.",var)
        col_range <- paste0("[",min(df[[var]], na.rm = T), ",", max(df[[var]], na.rm = T), "]")
    
        r2d3::r2d3("scatter_matrix.js", 
                      data= df, d3_version = "3", 
                      css = "scatter_matrix.css", 
                      options = list(exclude = var, 
                                     col = col, 
                                     col_range = col_range))
    }
    

    它允许您从 R 中选择您感兴趣的数据和变量,例如

    plot_d3sc(small_cars, "cyl")
    plot_d3sc(small_cars, "mpg")
    

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 2016-07-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 2019-08-28
      • 2022-01-10
      相关资源
      最近更新 更多