将绘图输出居中到 html

Art*_*lov 2 r plotly

我正在以编程方式将一个plotly小部件写入 html。但是,我似乎找不到将结果图居中的选项。这是一个有代表性的例子:

library( ggplot2 )

gg <- ggplot( mtcars, aes( x=mpg, y=wt ) ) + geom_point()
pp <- plotly::ggplotly( gg, width=300, height=300 )
htmlwidgets::saveWidget( pp, "test.html" )
Run Code Online (Sandbox Code Playgroud)

请注意,结果输出在页面上左对齐:

在此输入图像描述

ggplotly我已经浏览了、plotly::layout和的选项saveWidget,但没有立即明显的方法来使情节居中。过去,我将plotly元素包装在 Rmarkdown 文档中,并使用 markdown 关键字将图居中。然而,当前plotly输出是作为更大框架的一部分动态生成的,将其包装在 Rmarkdown 中并不简单。将小部件写入 .html 时有没有办法引入居中标签plotly

Art*_*lov 7

我发现的最简单的方法是使用package.json将 的输出包装在标签ggplotly内。可以使用同一包将生成的 HTML 对象保存到文件中:divhtmltoolssave_html

pp <- plotly::ggplotly( gg, width=300, height=300 )    # As before
ppc <- htmltools::div( pp, align="center" )  # Result is now an HTML object
htmltools::save_html( ppc, "test.html" )     # Use in place of htmlwidgets::saveWidget()
Run Code Online (Sandbox Code Playgroud)

这是结果,现在已正确居中:

在此输入图像描述