rstudio / reticulate

R Interface to Python
https://rstudio.github.io/reticulate
Apache License 2.0
1.68k stars 328 forks source link

[knitr] Duplicated plotly graph - intermediary plot shoud probably be hidden #1468

Open cderv opened 1 year ago

cderv commented 1 year ago

From https://github.com/quarto-dev/quarto-cli/issues/4507 - idea is to try the examples at https://plotly.com/python/sliders/

---
title: "plotly"
output: html_document
---

```{python}
#| echo: false
import plotly.graph_objects as go
import numpy as np

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(0, 5, 0.1):
    fig.add_trace(
        go.Scatter(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name="𝜈 = " + str(step),
            x=np.arange(0, 10, 0.01),
            y=np.sin(step * np.arange(0, 10, 0.01))))

# Make 10th trace visible
fig.data[10].visible = True

# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="update",
        args=[{"visible": [False] * len(fig.data)},
              {"title": "Slider switched to step: " + str(i)}],  # layout attribute
    )
    step["args"][0]["visible"][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=10,
    currentvalue={"prefix": "Frequency: "},
    pad={"t": 50},
    steps=steps
)]

fig.update_layout(
    sliders=sliders
)

fig.show()


But rendering this in R Markdown documents (or quarto), will end up with more plot than expected. 

Is this expected and it should somehow be dealt with in code chunk itself ? Or should there be a way to hide intermediary plots by default ? 
![image](https://github.com/rstudio/reticulate/assets/6791940/3dfd811d-50a5-44fb-bc93-2afa79c3e86d)
t-kalinowski commented 8 months ago

Thanks, I can reproduce.

In principle I agree that we should suppress auto-printing of the intermediate figures here, but changing the auto-printing semantics here is going to be a breaking change which we'll have to do thoughtfully.

For now, users can explicitly disable printing of intermediate plots by enabling jupyter_compat=TRUE mode. In this mode, only the very last expression in a chunk gets auto-printed, and only if it doesn't end with a trailing ;.

E.g., updating the chunk like:

```{python}
#| jupyter_compat: true
#| echo: false
import plotly.graph_objects as go
import numpy as np
.... (same as before)

image

cderv commented 8 months ago

Thanks ! I did not know about this jupyter_compat mode.

t-kalinowski commented 8 months ago

You may want to have a peek at ?reticulate::eng_python. We recently updated the help page to comprehensively list all the knitr options we support.