0

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. Is there a way to do this in r2d3? It doesn't save each plot as an object which you can arrange in a grid.

halfer
  • 19,824
  • 17
  • 99
  • 186
DiamondJoe12
  • 1,879
  • 7
  • 33
  • 81
  • So RMarkdown has styling abilities? Assuming that the graph is being appended to an element, in that case, what's stopping you from doing the same with your JS code with some CSS? – LeoDog896 Nov 14 '22 at 16:46
  • My issue is that the two-side by side graphs I'm trying to display have different data, and the r2d3 render only lets you specify one data source at a time. i.e. I don't think you feed a js script with two data sources. For that reason, I want to render the charts separately, but then pair them side by side. – DiamondJoe12 Nov 17 '22 at 15:46

1 Answers1

2

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.

pholzm
  • 1,719
  • 4
  • 11