R:编织rmarkDown中的ggplotly生成的数字列表

发布于 2025-02-08 21:27:08 字数 781 浏览 1 评论 0原文

我已经在stackoverflow中搜索过,并且有类似的问题,但是在我的情况下,答案没有用。

我想生成一个图列表,并通过编织rmarkDown文件将其输出HTML。

这是一个非常简单的演示代码:

library(ggplot2)
library(plotly)
DF <- data.frame(A = c(1:10), B = c(1:10), C = (1:10))
myplots <- vector('list', ncol(DF))

for (i in 1: dim(DF)[2]) {
  p = ggplot(DF, aes(x = DF[, i], y = C)) +
    geom_point() 
  myplots[[i]] = plotly::ggplotly(p)
}

myplots[[1]]
myplots[[2]]
myplots[[3]]

如果我索引它们,则可以将它们绘制在HTML文件中。

myplots[[1]]
myplots[[2]]
myplots[[3]]

但是,如果我直接使用列表对象或循环循环,则该方法均无效:

# method 1
myplots

# method 2
for (i in seq_along(myplots)) print(myplots[[i]])

#nethod 3

for (i in 1:length(myplots)) print(myplots[[i]])

我不明白问题。非常感谢您的帮助。

I have searched in stackoverflow, and there are similar questions, but the answers did not work in my case.

I want to generate a list of plots, and output them in HTML by knitting Rmarkdown file.

Here is a very simple demo code:

library(ggplot2)
library(plotly)
DF <- data.frame(A = c(1:10), B = c(1:10), C = (1:10))
myplots <- vector('list', ncol(DF))

for (i in 1: dim(DF)[2]) {
  p = ggplot(DF, aes(x = DF[, i], y = C)) +
    geom_point() 
  myplots[[i]] = plotly::ggplotly(p)
}

myplots[[1]]
myplots[[2]]
myplots[[3]]

If I index them, they can be plotted in HTML file.

myplots[[1]]
myplots[[2]]
myplots[[3]]

However, if I directly use the list object or loop it, none of the method worked:

# method 1
myplots

# method 2
for (i in seq_along(myplots)) print(myplots[[i]])

#nethod 3

for (i in 1:length(myplots)) print(myplots[[i]])

I don't understand the problem. Thanks a lot for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

洒一地阳光 2025-02-15 21:27:08

这是我的完整答案,非常感谢 @user2554330

我需要首先将列表转换为tagList,然后将其转换为plotly htmlwidget object。

library(ggplot2)
library(plotly)
DF <- data.frame(A = c(1:10), B = c(1:10), C = (1:10))
myplots <- htmltools::tagList()

for (i in 1: dim(DF)[2]) {
  p = ggplot(DF, aes(x = DF[, i], y = C)) +
    geom_point() 
  myplots[[i]] = plotly::as_widget(plotly::ggplotly(p))
}

myplots

Here is my complete answer, thanks a lot @user2554330

I need to first convert the list into taglist, and then convert it into a plotly htmlwidget object.

library(ggplot2)
library(plotly)
DF <- data.frame(A = c(1:10), B = c(1:10), C = (1:10))
myplots <- htmltools::tagList()

for (i in 1: dim(DF)[2]) {
  p = ggplot(DF, aes(x = DF[, i], y = C)) +
    geom_point() 
  myplots[[i]] = plotly::as_widget(plotly::ggplotly(p))
}

myplots
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文