我正在关注集成ggplot2和d3的简单教程。我正在本教程网站(http://timelyportfolio.github.io/gridSVG_intro/)上专门研究方法2。我试图复制交互式情节(这是该页面上的最后一个情节)。
我使用了相同的语法,并将其插入到.R文件中,如下所示:
library(gridSVG)
library(ggplot2)
library(XML)
library(rjson)
set.seed(955)
dat <- data.frame(cond = rep(c("A", "B"), each=10), xvar = 1:20 + rnorm(20,sd=3), yvar = 1:20 + rnorm(20,sd=3))
g4 = ggplot(dat, aes(x=xvar, y=yvar)) + geom_smooth() + geom_point(shape=19, aes(color = cond), size=5)
g4
g4.svg <- grid.export("plot1.svg",addClasses=TRUE)
cat(saveXML(g4.svg$svg))
cat(
'<script> ourdata=',
rjson::toJSON(apply(g4$data,MARGIN=1,FUN=function(x)return(list(x)))),
'</script>'
)
cat(
'<script> dataToBind = ',
'd3.entries(ourdata.map(function(d,i) {return d[0]}))',
'</script>'
)
cat(
'<script>\n',
'scatterPoints = d3.select(".points").selectAll("use");\n',
'scatterPoints.data(dataToBind)',
'</script>\n'
)
cat('<script>\n',
'scatterPoints
.on("mouseover", function(d) {
//Create the tooltip label
var tooltip = d3.select(this.parentNode).append("g");
tooltip
.attr("id","tooltip")
.attr("transform","translate("+(d3.select(this).attr("x")+10)+","+d3.select(this).attr("y")+")")
.append("rect")
.attr("stroke","white")
.attr("stroke-opacity",.5)
.attr("fill","white")
.attr("fill-opacity",.5)
.attr("height",30)
.attr("width",50)
.attr("rx",5)
.attr("x",2)
.attr("y",5);
tooltip.append("text")
.attr("transform","scale(1,-1)")
.attr("x",5)
.attr("y",-22)
.attr("text-anchor","start")
.attr("stroke","gray")
.attr("fill","gray")
.attr("fill-opacity",1)
.attr("opacity",1)
.text("x:" + Math.round(d.value.xvar*100)/100);
tooltip.append("text")
.attr("transform","scale(1,-1)")
.attr("x",5)
.attr("y",-10)
.attr("text-anchor","start")
.attr("stroke","gray")
.attr("fill","gray")
.attr("fill-opacity",1)
.attr("opacity",1)
.text("y:" + Math.round(d.value.yvar*100)/100);
})
.on("mouseout", function(d) {
d3.select("#tooltip").remove();
});',
'</script>'
)
我从这个脚本得到的唯一输出是plot1.svg文件。但是,当我在浏览器中打开它时(尝试过Safari和谷歌浏览器),它是图像的停滞版本。
我会给作者发电子邮件。但该联系信息不可用。它本来是一个简单的教程,所以我希望它是一个简单的解决方案!
我对这个交互式组件很陌生。但是,我一步一步地遵循了指示,并且不确定我可能忽略了什么。任何与解决此问题相关的支持或信息都将非常感谢!
答案 0 :(得分:6)
<强> EDITS 强>
所以,我最后安装了R,看看原来的答案出错了。我很接近。我错过了saveXML
来电,而@ arvi1000指出我没有来源d3
。这是一个完整的修复示例。我刚用R 3.2.3运行它,它会在你的工作目录中生成一个myAwesomePlot.html
:
library(gridSVG)
library(ggplot2)
library(XML)
library(rjson)
set.seed(955)
dat <- data.frame(cond = rep(c("A", "B"), each=10), xvar = 1:20 + rnorm(20,sd=3), yvar = 1:20 + rnorm(20,sd=3))
g4 = ggplot(dat, aes(x=xvar, y=yvar)) + geom_smooth() + geom_point(shape=19, aes(color = cond), size=5)
# what does this line do? It writes the SVG to the file "plot1.svg"?
g4.svg <- grid.export("", addClasses=TRUE)
# create a valid html file
cat("<html><head><script src='http://d3js.org/d3.v3.min.js'></script></head><body>", file="myAwesomePlot.html")
# I'm assuming this gets the svg content and can write it to a file
cat(saveXML(g4.svg$svg), file="myAwesomePlot.html", append=TRUE)
cat(
'<script> ourdata=',
rjson::toJSON(apply(g4$data,MARGIN=1,FUN=function(x)return(list(x)))),
'</script>', file="myAwesomePlot.html", append=TRUE
)
cat(
'<script> dataToBind = ',
'd3.entries(ourdata.map(function(d,i) {return d[0]}))',
'</script>'
, file="myAwesomePlot.html", append=TRUE)
cat(
'<script>\n',
'scatterPoints = d3.select(".points").selectAll("use");\n',
'scatterPoints.data(dataToBind)',
'</script>\n'
, file="myAwesomePlot.html", append=TRUE)
cat('<script>\n',
'scatterPoints
.on("mouseover", function(d) {
//Create the tooltip label
var tooltip = d3.select(this.parentNode).append("g");
tooltip
.attr("id","tooltip")
.attr("transform","translate("+(d3.select(this).attr("x")+10)+","+d3.select(this).attr("y")+")")
.append("rect")
.attr("stroke","white")
.attr("stroke-opacity",.5)
.attr("fill","white")
.attr("fill-opacity",.5)
.attr("height",30)
.attr("width",50)
.attr("rx",5)
.attr("x",2)
.attr("y",5);
tooltip.append("text")
.attr("transform","scale(1,-1)")
.attr("x",5)
.attr("y",-22)
.attr("text-anchor","start")
.attr("stroke","gray")
.attr("fill","gray")
.attr("fill-opacity",1)
.attr("opacity",1)
.text("x:" + Math.round(d.value.xvar*100)/100);
tooltip.append("text")
.attr("transform","scale(1,-1)")
.attr("x",5)
.attr("y",-10)
.attr("text-anchor","start")
.attr("stroke","gray")
.attr("fill","gray")
.attr("fill-opacity",1)
.attr("opacity",1)
.text("y:" + Math.round(d.value.yvar*100)/100);
})
.on("mouseout", function(d) {
d3.select("#tooltip").remove();
});',
'</script>'
, file="myAwesomePlot.html", append=TRUE)
# close out file
cat("</body></html>", file="myAwesomePlot.html", append=TRUE)
原始答案
自从我完成R
编程以来已经有一段时间了,但那些cat
函数看起来并不正确。他们会写入标准输出,而不是写入文件。我的猜测是grid.export
只写svg
文件,其他一切都被删除。一目了然,我假设您打算将此代码运行为:
R myRCode.R > outPutFile.svg
这样stdout就会重定向到一个文件中。
我尝试重新编译代码并将所有内容明确写入html
文件:
library(gridSVG)
library(ggplot2)
library(XML)
library(rjson)
set.seed(955)
dat <- data.frame(cond = rep(c("A", "B"), each=10), xvar = 1:20 + rnorm(20,sd=3), yvar = 1:20 + rnorm(20,sd=3))
g4 = ggplot(dat, aes(x=xvar, y=yvar)) + geom_smooth() + geom_point(shape=19, aes(color = cond), size=5)
g4
// what does this line do? It writes the SVG to the file "plot1.svg"?
g4.svg <- grid.export("plot1.svg",addClasses=TRUE)
// create a valid html file
cat("<html><head></head><body>", file="myAwesomePlot.html")
// I'm assuming this gets the svg content and can write it to a file
cat(g4.svg$svg, file="myAwesomePlot.html")
cat(
'<script> ourdata=',
rjson::toJSON(apply(g4$data,MARGIN=1,FUN=function(x)return(list(x)))),
'</script>', file="myAwesomePlot.html"
)
// etc, rest of JavaScript
// close out file
cat("</body></html>", file="myAwesomePlot.html")
答案 1 :(得分:5)
cat
,正如你所拥有的那样,在简单的R脚本中,只是输出到控制台,正如@Mark所说。要解决1)您的最终html文档必须包含:<script src="http://d3js.org/d3.v3.min.js"></script>
或等效文件。
要解决2),您可以使用Rmarkdown .Rmd文件并将所有内容放入块中。
在扩展名为.Rmd的文件中,使用以下行开始块:
```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE}
接下来,请确保将D3库包含在此行中:
cat('<script src="http://d3js.org/d3.v3.min.js"></script>')
然后添加上面的所有代码,然后结束块:
```
如果您在Rstudio中执行此操作,则可以点击“编织HTML&#39;”。否则,您可以从控制台或其他.R脚本中使用knitr::knit2html
或rmarkdown::render
。
答案 2 :(得分:1)
如果您不喜欢@ arvi1000建议使用knitr
(这是一个很好的建议),您可以在第一个sink(file = "myfile.html")
声明之前使用cat()
将所有输出写入myfile.html
。最后,只需添加语句sink()
即可开始写回标准输出。
就像@ arvi1000所说,你也错过了D3.js库的链接。按照他们的指示,将cat('<script src="http://d3js.org/d3.v3.min.js"></script>')
作为您的第一个cat()
声明。您可能还需要遵循@ Mark关于创建有效HTML文件的建议。
老实说,最简单的方法是使用knitr
。我已经包含了一个有效的.Rmd文件的内容,它将生成D3.js图。只需在包含以下代码的.Rmd文件上运行knitr::knit2html()
即可。我添加了一些评论,我对正在发生的事情有了最好的解释(我从未对D3.js做过ggplot,所以这对我来说是一次很酷的学习经历!)
```{r echo = FALSE, message = FALSE, fig.keep = 'none'}
library(gridSVG)
library(ggplot2)
library(XML)
library(rjson)
# create a plot with some fake data
set.seed(955)
dat <- data.frame(cond = rep(c("A", "B"), each=10), xvar = 1:20 + rnorm(20,sd=3), yvar = 1:20 + rnorm(20,sd=3))
g4 = ggplot(dat, aes(x=xvar, y=yvar)) + geom_smooth() + geom_point(shape=19, aes(color = cond), size=5)
# you need to print the plot in order to capture it with grid.export
g4
# exporting the plot to a .svg file
g4.svg <- grid.export("plot1.svg",addClasses=TRUE)
```
```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE}
# load the d3.js script
cat('<script src="http://d3js.org/d3.v3.min.js"></script>')
# convert the svg file to an XML string and print it
cat(saveXML(g4.svg$svg))
# looks like you convert the ggplot object data to JSON for use by d3.js
# looks like the aesthetics are included here? I don't seem them defined
# anywhere else
cat(
'<script> ourdata=',
rjson::toJSON(apply(g4$data,MARGIN=1,FUN=function(x)return(list(x)))),
'</script>'
)
# d3.js data definition
cat(
'<script> dataToBind = ',
'd3.entries(ourdata.map(function(d,i) {return d[0]}))',
'</script>'
)
# d3.js scatter plot
cat(
'<script>\n',
'scatterPoints = d3.select(".points").selectAll("use");\n',
'scatterPoints.data(dataToBind)',
'</script>\n'
)
# d3.js code to support the hover tooltips (hover over a point on the plot)
# this is apparently ALL for the tooltip
cat('<script>\n',
'scatterPoints
.on("mouseover", function(d) {
//Create the tooltip label
var tooltip = d3.select(this.parentNode).append("g");
tooltip
.attr("id","tooltip")
.attr("transform","translate("+(d3.select(this).attr("x")+10)+","+d3.select(this).attr("y")+")")
.append("rect")
.attr("stroke","white")
.attr("stroke-opacity",.5)
.attr("fill","white")
.attr("fill-opacity",.5)
.attr("height",30)
.attr("width",50)
.attr("rx",5)
.attr("x",2)
.attr("y",5);
tooltip.append("text")
.attr("transform","scale(1,-1)")
.attr("x",5)
.attr("y",-22)
.attr("text-anchor","start")
.attr("stroke","gray")
.attr("fill","gray")
.attr("fill-opacity",1)
.attr("opacity",1)
.text("x:" + Math.round(d.value.xvar*100)/100);
tooltip.append("text")
.attr("transform","scale(1,-1)")
.attr("x",5)
.attr("y",-10)
.attr("text-anchor","start")
.attr("stroke","gray")
.attr("fill","gray")
.attr("fill-opacity",1)
.attr("opacity",1)
.text("y:" + Math.round(d.value.yvar*100)/100);
})
.on("mouseout", function(d) {
d3.select("#tooltip").remove();
});',
'</script>'
)
```