Home > Net >  How can I supress unwanted plotly figs from printing?
How can I supress unwanted plotly figs from printing?

Time:10-02

I'm having trouble plotting a graph (using python and plotly) in an r markdown document I'm working on. Using the code below, I get five figures printed in differing states, e.g.

  1. the first is without any horizontal lines,
  2. the second has the first horizontal line,
  3. the third figure has the second horizontal line
  4. the fourth has the corrected axis names, and
  5. the last print being the correct one (associated with fig.show()).

Is there a way to 'mute' the output until the final line of code? Perhaps this is an issue connected with reticulate?

Thanks!

# plotting the bar chart
fig = px.bar(df2122, x="DateYear", y="kg", template="plotly_white") 
fig.add_hline(y=169117.6839, annotation_text="Monthly average 2019/20", annotation_position="top right")
fig.add_hline(y=75584.48002, annotation_text="Monthly average 2020/21", annotation_position="top right")

fig.update_layout(xaxis_title="Date", yaxis_title="kg")

# showing the plot
fig.show()

CodePudding user response:

I used pandas and numpy instead of plotly, to keep it simple. In your Rmarkdown chunk, you can use include = FALSE, to mute the R chunk where your python plot is generated. You can put each plot in it's own chunk, but each chunk will need a unique name(chunk1, chunk2) or you can put the first 4 plots in the R chunk with include = FALSE and the one you want to display in a plain chunk. See the code below has 2 plots, but only 1 of them displays once the document is rendered.

---
title: "Untitled"
author: "author"
date: "10/1/2021"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
```

```{python, chunk1}
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('1/1/2000',
   periods=10), columns=list('ABCD'))

df.plot()
```

```{python, chunk2, include = FALSE}
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('1/1/2000',
   periods=10), columns=list('ABCD'))

df.plot()
```

enter image description here

  • Related