本文介绍了如何显示具有动态创建的选项卡和for循环的ggplotly图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有R markdown文档,我想动态创建带有ggplotly图形的选项卡

I have R markdown document and I want to dynamically create tabs with ggplotly graphics inside them

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
library(ggplot2)
library(plotly)
```

```{r}
fig=ggplot(cars)+geom_point(aes(speed, dist))
```

# level 1
## level 2{.tabset .tabset-pills}

```{r echo=FALSE, results='asis'}

for (h in 1:3){
  cat("###", h,'{-}',  '\n\n')
 ggplotly(fig)
  cat( '\n\n')
}
```

我了解它与正常的 ggplot 图不同,我在此处查看了解决方案:在此处输入链接描述,但它对我不起作用

I understand that it is different from normal ggplot graph and I looked at the solutions here: enter link description here but It did not work for me

推荐答案

遵循此 post 可以像这样实现:

Following this post this can be achieved like so:

编辑:遵循此帖子添加了两个函数以将 fig.width fig.height 传递给ggplotly.

Following this post I added two functions to pass the fig.width and fig.height to ggplotly.

:添加了代码以另外使用 plotly :: subplot s.

Edit 2: Added the code to additionally use plotly::subplots.

---
title: test
date: "20 5 2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
library(ggplot2)
library(plotly)
```

```{r, echo=FALSE}
# Get the current figure size in pixels:
get_w <- function() {
  with(knitr::opts_current$get(c("fig.width", "dpi", "fig.retina")),
       fig.width*dpi/fig.retina)
}

get_h <- function() {
  with(knitr::opts_current$get(c("fig.height", "dpi", "fig.retina")),
       fig.height*dpi/fig.retina)
}
```

```{r}
fig <- ggplot(cars) + 
  geom_point(aes(speed, dist))
```

# level 1

## level 2 {.tabset .tabset-pills}

```{r, include=FALSE}
htmltools::tagList(ggplotly(fig))
```

```{r echo=FALSE, results='asis', fig.width=4, fig.height=4}
fig <- ggplotly(fig, width = get_w(), height = get_h())
for (h in 1:3) {
  cat("###", h, '{-}',  '\n\n')
  print(htmltools::tagList(plotly::subplot(fig, fig, nrows=2, heights = c(0.1, 0.9))))
  cat( '\n\n')
}
```

这篇关于如何显示具有动态创建的选项卡和for循环的ggplotly图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:08