Home  >  Q&A  >  body text

r2d3 in R: How to display two plots side by side on the same line?

<p>Using the r2d3 package, I can render a simple d3.js chart in RMarkdown like this: </p> <p><strong>barchart.js</strong>:</p> <pre class="brush:php;toolbar:false;">// !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");</pre> <p><strong>RMarkdown</strong>: </p> <pre class="brush:php;toolbar:false;">{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")</pre> <p>However, let's say I want to draw the same chart simultaneously in RMarkdown (i.e. two charts side by side). Is there a way to do this? Using simple RMarkdown is easy since you can save the graph and then arrange it in a grid. But is there a way for r2d3 to do this? It does not save each shape as an object that can be arranged in a grid. </p>
P粉543344381P粉543344381412 days ago614

reply all(1)I'll reply

  • P粉786432579

    P粉7864325792023-09-04 14:21:52

    I guess there are multiple ways to do this. One option is to use 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)
    )

    BTW - bscols is also very useful for scheduling any interactive html widget, and can solve most cases where "normal" Rmd output cannot be easily scheduled.

    reply
    0
  • Cancelreply