Home > Back-end >  r2d3 in R: how to make two charts next to each other?
r2d3 in R: how to make two charts next to each other?

Time:11-18

Using the r2d3 package, I can render a simple d3.js chart in RMarkdown using something like this:

barchart.js:

// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)

var barHeight = Math.floor(height / data.length);

svg
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("width", function (d) {
    return d * width;
  })
  .attr("height", barHeight)
  .attr("y", function (d, i) {
    return i * barHeight;
  })
  .attr("fill", "steelblue");

RMarkdown:

```{r out.width='100%', fig.height=4}
library(r2d3)
r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js")
```

But, let's say I wanted to draw the same chart, side-by-side (i.e. two charts next to one another in RMarkdown). Is there a way to do this? Doing this using simple RMarkdown is easy since you can save plots and then arrange in a grid; I don't see a way to do this in r2d3 since it doesn't save each plot as an object which you can arrange in a grid? Thank you.

CodePudding user response:

I guess there are multiple ways of doing it. One option is using the Bootstrap Columns implemented in the crosstalk package:


library(r2d3)
library(crosstalk)

crosstalk::bscols(
  widths = c(6, 6),
   r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js", 
        width = 300, height = 200),
   r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js", 
        width = 300, height = 200)
)

enter image description here

On a side note - bscols is pretty useful to arrange any interactive html-widgets as well, and can solve most situations, where the "normal" Rmd output cannot be easily arranged.

  • Related