Passing fig.width into a taglist

徘徊边缘 提交于 2020-07-07 22:39:36

问题


The rgl widget responds to the figure width and height specified in knitr code chunk options, e.g.

```{r fig.width=2, fig.height=2}
library(rgl); example(plot3d);
rglwidget()
```

gives a small plot (192 x 192 on my screen). However, if I put rglwidget() in a browsable tagList, it doesn't:

```{r fig.width=2, fig.height=2}
library(rgl); example(plot3d)
library(htmltools)
browsable(tagList(rglwidget(), rglwidget()))
```

This gives two full size widgets. Debugging the Javascript shows that each is being initialized as 960 by 500, not 192 by 192 as in the first example.

Is there a way to say that I want the width and height values to be passed into the widgets in the tagList?

P.S. This has nothing to do with rgl; leaflet has the same problem in

```{r fig.width=2, fig.height=2}
library(leaflet); library(htmltools)
browsable(tagList(leaflet() %>% addTiles())
```

回答1:


Since code in a chunk can read the options for the chunk, probably the best solution here is to write small functions that obtain the size of the figure in pixels, and use those in explicit settings in the widget.

For example,

```{r fig.width=2, fig.height=2}
library(leaflet); library(htmltools)

# This one is too big:
browsable(tagList(leaflet() %>% addTiles()))

# Get the current figure size in pixels:
w <- function() 
  with(knitr::opts_current$get(c("fig.width", "dpi", "fig.retina")),
       fig.width*dpi/fig.retina)
h <- function() 
  with(knitr::opts_current$get(c("fig.height", "dpi", "fig.retina")),
       fig.height*dpi/fig.retina)

# This is what I wanted:
browsable(tagList(leaflet(width = w(), height = h()) %>% addTiles()))
```


来源:https://stackoverflow.com/questions/42532129/passing-fig-width-into-a-taglist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!