gpt4 book ai didi

python - 如何在 Rmarkdown 文档中显示来自 Python 代码的几何对象?

转载 作者:行者123 更新时间:2023-12-05 05:51:33 24 4
gpt4 key购买 nike

我想在编织后在我的 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>

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

此外,我有兴趣在查看器/绘图 Pane 中显示它。

最佳答案

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

```{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 block 显示它:

```{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.

不过你可以无视它,它还是画出了点:

enter image description here enter image description here

完整代码:

---
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)
```

关于python - 如何在 Rmarkdown 文档中显示来自 Python 代码的几何对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70365164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com