mat*_*mat 5 javascript r ggplot2 r-markdown r-plotly
我有一个带有简单散点图(例如地图)的 Rmarkdown,我希望用户能够通过输入提供一些任意x坐标y,并将这些坐标绘制在图表上(在下面的示例中以红色显示)。问题是,我没有闪亮的服务器,所以我不能依赖这个选项。是否有一个实现,例如,通过 javascript 或其他东西?
这就是我所拥有的:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
```
```{r fig.height=4, fig.width=4}
X <- data.frame(x = 1:10, y = 1:10)
gg <- ggplot(X, aes(x, y)) + geom_point()
ggplotly(gg)
```
Run Code Online (Sandbox Code Playgroud)
这就是我正在寻找的:
编辑
上面的例子是一个简化。实际上,网格是360x240,坐标只能是整数。
编辑2 @JohanRosa 已经通过完全在plotly.js 上重建绘图提供了一个很好的答案。然而,我的 ggplot 实际上相当复杂,而且我有很多。因此,将它们重建到plotly.js 对我来说是相当复杂的。这就是我正在寻找一种可以直接在我拥有的 ggplot(ly) 上工作的解决方案的原因。
我们可以使用htmlwidgets::onRender将自定义 JS 代码注入到您的 ggplotly 对象中。
我重用了 @JohanRosa 的输入(谢谢!+1),并向容器 div 提供了一个 id 以监听输入。此外,我使用Plotly.restyle来避免重绘绘图。
请检查以下内容:
---
title: "ggplotly user inputs"
output: html_document
---
:::{#inputcontainerid .input-container}
:::{.xs}
### X coordinate
<input type='number' value=5 id='x1' class='x'>
<input type='number' value=2.5 id='x2' class='x'>
<input type='number' value=7.5 id='x3' class='x'>
:::
:::{.ys}
### Y coordinate
<input type='number' value=10 id='y1'>
<input type='number' value=5 id='y2'>
<input type='number' value=2.5 id='y3'>
:::
:::
<!-- css configuration to arrange the inputs -->
```{css, echo = FALSE}
input {
display: block;
}
.xs, .ys {
display: inline-block;
}
```
```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
library(htmlwidgets)
```
```{r out.width='100%', echo=FALSE}
X <- data.frame(x = 1:10, y = 1:10)
JS <- "
function(el, x){
var id = el.getAttribute('id');
var gd = document.getElementById(id);
let defaultInputs = {
x: [$('#x1').val(), $('#x2').val(), $('#x3').val()],
y: [$('#y1').val(), $('#y2').val(), $('#y3').val()],
mode: 'markers',
type: 'scatter',
name: 'user'
};
Plotly.addTraces(gd, defaultInputs);
document.getElementById('inputcontainerid').addEventListener('input', function(event){
let userInputs = {
x: [[$('#x1').val(), $('#x2').val(), $('#x3').val()]],
y: [[$('#y1').val(), $('#y2').val(), $('#y3').val()]]
};
Plotly.restyle(gd, userInputs, 1);
});
}
"
gg <- ggplot(X, aes(x, y)) + geom_point()
ggplotly(gg) %>%
layout(xaxis = list(autorange = TRUE), yaxis = list(autorange = TRUE)) %>%
onRender(jsCode = JS)
```
Run Code Online (Sandbox Code Playgroud)
有关其他信息,请参阅Carson Sievert 的书《使用 R、plotly 和闪亮的交互式基于 Web 的数据可视化》中的第 5 章“JavaScript 中的事件处理” 。
| 归档时间: |
|
| 查看次数: |
592 次 |
| 最近记录: |