如何在R Markdown中让两个Plotly图表并排显示?
解决R Markdown中Plotly图表并排显示的问题
普通的fig.show="hold"和out.width参数仅对静态图片(如ggplot、基础绘图)生效,Plotly生成的是交互式HTML组件,这类组件不受knitr的图片布局参数控制,需要通过HTML/CSS来实现并排。以下是几种可行的方法:
方法1:Flex布局(推荐,适配性强)
利用htmltools包创建flex容器,让两个图表平分宽度:
library(plotly) library(htmltools) # 定义两个Plotly图表 p1 <- plot_ly(x = iris$Species, y = iris$Sepal.Length, type = "bar") p2 <- plot_ly(x = iris$Species, y = iris$Petal.Length, type = "bar") # Flex布局实现并排 div( style = "display: flex; gap: 15px; margin: 10px 0;", div(p1, style = "flex: 1;"), div(p2, style = "flex: 1;") )
方法2:Inline-block样式
通过设置display: inline-block让图表横向排列:
library(plotly) library(htmltools) p1 <- plot_ly(x = iris$Species, y = iris$Sepal.Length, type = "bar") p2 <- plot_ly(x = iris$Species, y = iris$Petal.Length, type = "bar") tagList( tags$div(p1, style = "display: inline-block; width: 49%; vertical-align: top;"), tags$div(p2, style = "display: inline-block; width: 49%; vertical-align: top;") )
方法3:Bootstrap网格(适配默认HTML模板)
如果你的R Markdown使用默认的html_document模板(自带Bootstrap),可以用网格系统快速布局:
library(plotly) library(htmltools) p1 <- plot_ly(x = iris$Species, y = iris$Sepal.Length, type = "bar") p2 <- plot_ly(x = iris$Species, y = iris$Petal.Length, type = "bar") div( class = "row", div(class = "col-sm-6", p1), div(class = "col-sm-6", p2) )
关键说明
Plotly图表本质是独立的HTML元素,knitr的图片布局参数无法直接控制它们的位置,必须通过包裹HTML容器并设置CSS样式来实现并排效果。
内容的提问来源于stack exchange,提问作者nateroe
相关产品推荐
相关产品推荐

