r2d3 in R: How to display two plots side by side on the same line?
P粉543344381
2023-09-03 16:23:03
<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>
I guess there are multiple ways to do this. One option is to use Bootstrap Columns implemented in the
crosstalk
package: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.