我在使用 highcharter 库 通过循环绘制各种图的想法上遇到了一些麻烦。我的代码如下所示:
这里我上传文件并将所有 NA 值转换为“na”字符串。
DT <- fread(file, sep='auto',na.strings=c("Na","-",""), blank.lines.skip=TRUE, stringsAsFactors = FALSE)
DTT <- DT
```
```{r, echo=F, results='asis'}
for(i in seq_along(DTT)) {
DTT[[i]] <- sapply(DTT[[i]], function(x) if(is.na(x)) x <- "na" else x <- x)
DTT[[i]] <- as.factor(DTT[[i]])
}
我尝试做一个循环:
for(i in seq_along(DTT)) {
hc <- highchart() %>%
hc_title(text = 'prueba',
style = list(fontSize = "15px")) %>%
hc_chart(type = 'pie') %>%
hc_xAxis(categories = DTT[[i]]) %>%
hc_add_series(DTT[[i]], name = "Market", showInLegend = FALSE)
hc
}
我还尝试创建一个函数并通过循环调用它,但两者都不起作用。
最后,我使用了 lapply 函数
将绘图函数应用于数据帧的所有列,但效果不佳。也许我没有正确执行 lapply 过程。
gethc <- function(DT) {
hc <- highchart() %>%
hc_title(text = 'prueba',
style = list(fontSize = "15px")) %>%
hc_chart(type = 'pie') %>%
hc_xAxis(categories = DT) %>%
hc_add_series(DT, name = "Market", showInLegend = FALSE)
hc
}
lapply(DTT, gethc)
搜索我发现:Plot inside a loop using highcharter
您必须在循环内使用 print,因为自动打印已关闭,但它没有打印任何内容。
示例:
DT <- mtcars
for(i in seq_along(DT)) {
DT[[i]] <- sapply(DT[[i]], function(x) if(is.na(x)) x <- "na" else x <- x)
}
gethc <- function(i) {
hc <- highchart() %>%
hc_title(text = 'prueba',
style = list(fontSize = "15px")) %>%
hc_chart(type = 'pie') %>%
hc_xAxis(categories = DT[[i]]) %>%
hc_add_series(DT[[i]], name = "Market", showInLegend = FALSE)
print(hc)
}
for(i in seq_along(DT)) {
gethc(i)
}
这适用于 .R 程序,但不适用于 R Markdown
如果有人能解决这个问题,那将会非常有帮助。
最佳答案
看起来在 R MarkDown 中无法使用循环打印 highcharter 图表,但我找到了一种使用 htmltools 并创建 highcharter 图表列表以将它们发送到 的方法tagList
幸运的是现在可以正确打印所有内容。
DT <- mtcars
gethc <- function(i) {
hc <- highchart() %>%
hc_title(text = 'prueba',
style = list(fontSize = "15px")) %>%
hc_chart(type = 'pie') %>%
hc_xAxis(categories = DT[[i]]) %>%
hc_add_series(DT[[i]], name = "Market", showInLegend = FALSE)
hc
}
a = list()
for(i in seq_along(DT)) {
a[[i]] <- gethc(i)
}
htmltools::tagList(a)
关于r - Markdown R : Using highcharter to plot in a loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45592017/