【问题标题】:How to display a geometric object from Python code in a Rmarkdown document?如何在 Rmarkdown 文档中显示 Python 代码中的几何对象?
【发布时间】:2022-01-18 17:25:44
【问题描述】:

我想在编织后在我的 rmarkdown 文档中显示一个点(如 in this tutorial)。

可重现的例子:

---
title: "Reprex"
output: html_document
---

```{python}
# Import necessary geometric objects from shapely module
from shapely.geometry import Point, LineString, Polygon

# Create Point geometric object(s) with coordinates
point1 = Point(2.2, 4.2)

point1
```

使用这段代码,我只得到以下输出:

## <shapely.geometry.point.Point object at 0x0000000026EEA0B8>

我怎样才能显示点的图像?

另外,我有兴趣在查看器/绘图窗格中显示它。

【问题讨论】:

    标签: python r r-markdown reticulate


    【解决方案1】:

    首先,不确定这是否至关重要,但是,following the documentation,我们需要先添加这个块:

    ```{r setup, include=FALSE}
    library(knitr)
    library(reticulate)
    knitr::knit_engines$set(python = reticulate::eng_python)
    ```
    

    您想要获得的是特定于 Jupyter 的功能。我只能通过_repr_svg_() 函数将点转换为纯 SVG 来重现它:

    ```{python}
    from shapely.geometry import Point, LineString, Polygon, MultiPoint
    
    point1 = Point(2.2, 4.2)
    point2 = Point(7.2, -25.1)
    point3 = Point(9.26, -2.456)
    point3D = Point(9.26, -2.456, 0.57)
    
    multipoints = MultiPoint([point1, point2, point3, point3D])
    svg = multipoints._repr_svg_()
    
    # or, in your case
    
    svg = point1._repr_svg_()
    ```
    

    然后用 R 块显示它:

    ```{r}
    htmltools::HTML(py$svg)
    ```
    

    我尝试仅在 Python 端执行此操作(调用 r.HTML()),这只会导致文本输出。

    请注意,这将导致以下警告:

    sys:1: ShapelyDeprecationWarning: __len__ for multi-part geometries is deprecated and will be removed in Shapely 2.0. Check the length of the `geoms` property instead to get the  number of parts of a multi-part geometry.
    

    但你可以忽略它,它仍然会画点:

    完整代码:

    ---
    title: "Reprex"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    library(knitr)
    library(reticulate)
    knitr::knit_engines$set(python = reticulate::eng_python)
    ```
    
    ```{python}
    from shapely.geometry import Point, LineString, Polygon, MultiPoint
    
    point1 = Point(2.2, 4.2)
    point2 = Point(7.2, -25.1)
    point3 = Point(9.26, -2.456)
    point3D = Point(9.26, -2.456, 0.57)
    
    multipoints = MultiPoint([point1, point2, point3, point3D])
    svg = multipoints._repr_svg_()
    
    # or, in your case
    
    svg = point1._repr_svg_()
    ```
    
    ```{r}
    htmltools::HTML(py$svg)
    ```
    

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2017-01-25
      • 2018-10-14
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多