I have a jupyter notebook with interractive plotly plots. I am converting that notebook into slides using nbconvert. When I do so the plotly plots do not show up in the slides. I get the following tornado warnings as well
$ jupyter nbconvert presentation.ipynb --to slides --post serve
[NbConvertApp] Converting notebook presentation.ipynb to slides
[NbConvertApp] Writing 818538 bytes to presentation.slides.html
[NbConvertApp] Redirecting reveal.js requests to https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.1.0
Serving your slides at http://127.0.0.1:8000/presentation.slides.html
Use Control-C to stop this server
WARNING:tornado.access:404 GET /custom.css (127.0.0.1) 1.53ms
WARNING:tornado.access:404 GET /custom.css (127.0.0.1) 0.96ms
WARNING:tornado.access:404 GET /plotly.js (127.0.0.1) 0.84ms
To add insult to injury this worked yesterday and I don't think I changed anything substantial. I tried rebooting my browser and my machine and neither helped.
1) Check the JS console for errors and the Jupyter log if you are serving the slides via Jupyter. When you browse the slides.html, you may be getting
404 GET /files/mydir/plotly.js
put the plotly.js file in the directory where the slides.html is located (download e.g. https://cdn.plot.ly/plotly-latest.min.js and rename to plotly.js)
2) make sure you are specifying a Layout height and width in your Jupyter notebook e.g.
trace_data = [trace1]
layout = Layout(
autosize=False,
width=720,
height=480,
margin=Margin(
l=50,
r=50,
b=100,
t=100,
pad=4
),
bargroupgap=0.3
)
fig = Figure(data=trace_data, layout=layout)
Re-run your charts, check they appear properly in the notebook, save the notebook, re-run nbconvert.
You do not need to customize the custom.css and make a myreveal.tpl Reveal template and specify it on the nbconvert command line, but you can do so if you wish to customize your slides.
Following the code found here : https://nbviewer.jupyter.org/format/slides/github/tarokiritani/testjupyter/blob/master/test%20plotly.ipynb#/
I have found adding plotly.offline.init_notebook_mode(connected=True) into the same cell as the plotly.offline.(i)plot function works
You must have a plotly.js file in your directory where you are performing nbconvert. For some reason, "to html" will embed the plotly javascript into the HTML file, but "to slides" searches for a plotly.js file in the directory.
That said, you will have to template reveal.js to change dimensions of the slides depending on the size of your plot charts. That, or customize the dimension of the plotly graphs. If the slide are too big (or the other way around), the graphs will collapse into one line in the slides.
Related
I'd like to play audio on a remote Jupyter Notebook (like in Google Colab or a Binder-hosted Jupyterlab) but I can't figure out how. What I would like to get working is something like this:
from pydub import AudioSegment
from pydub.playback import play
start = 1000
end = 3000
audio = AudioSegment.from_file("someaudio.flac")
audio_piece = audio[start:end]
play(audio_piece)
With a playback package like simpleaudio installed, everything works fine on my local machine. But when I try to run this code in Google Colab, for example, I get this error message:
SimpleaudioError: Error opening PCM device. -- CODE: -2 -- MSG: No such file or directory
I tried several other audio packages but I always ran into some trouble. The only thing that works is IPython.display -> Audio. But I can't use this for my project because I don't want a player displayed (and because it doesn't seem to have the option to play segments of an audio file).
Does anyone know a solution for this?
For MyBinder-served sessions, you have to connect the audio playing ability to IPython abilities imported into the notebook or link the playing of audio to ipywidgets running in the notebook.
Example of playing a wav file in a MyBinder-served notebook
Go to here and press 'launch Binder'.
When the session spins up, paste this into a cell and run that cell:
# PLAY A WAV. BASED ON
# https://ipython.org/ipython-doc/stable/api/generated/IPython.display.html#IPython.display.Audio
from IPython.display import Audio, display
Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # From URL
# see https://ipython.org/ipython-doc/stable/api/generated/IPython.display.html#IPython.display.Audio
# for other options such as a file you upload to the remote MyBinder-served session
That will show a controller you can click 'play' to play the file found at the URL as the wav file.
See the source linked in the comments for more information, such as how you could play your own wav file.
To demo this in JupyterLab:
If you are starting fresh, click here to launch directly into JupyterLab. When that sessions spins up, open a new notebook and paste in the code above.
If you are already in a session provided by MyBinder in the classic notebook, click the 'Jupyter' logo in the upper left side above the notebook. The page will refresh and the JupyterLab interface will load and you can open a notebook there and paste in the above code.
The environment specified for those sessions isn't overly complex as you can see here.
Example of playing a tone in a MyBinder-served notebook
Similar to everything above; however, use this as the code block you paste into a cell:
# Generate a sound. BASED ON
# https://ipython.org/ipython-doc/stable/api/generated/IPython.display.html#IPython.display.Audio
import numpy as np
from IPython.display import Audio, display
framerate = 44100
t = np.linspace(0,5,framerate*5)
data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
Audio(data,rate=framerate)
Example if an interactive control via ipywidgets of audio-generation in a MyBinder-served notebook.
Click here to launch a session with the JupyterLab interface back by an environment with the necessary modules installed, and then run the following in a cell:
!curl -OL https://raw.githubusercontent.com/mlamoureux/PIMS_YRC/master/Widget_audio.ipynb
That will fetch a notebook that you can run, based on code described here.
Alternatively, you can use the classic interface by launching fresh to one or switching from the JupyterLab inferface back by using from the menubar, 'Help' > 'Launch Classic Notebook'.
(I believe the notebook used in this example is based on here, or vice versa. When I tried that one in the ipywidgets docs from a session that already had ipywidgets installed & not much else, I had to also install matplotlib along with ipywidgets via running %pip install matplotlib, because of the line import matplotlib.pyplot as plt.)
UPDATE: use pydub to edit audio via MyBinder and hear it played
This was added in response to the comments to the general answer. Specifically, pydub use is demonstrated using a different enviornment, since pydub needs ffmpeg.
Go here and click on 'launch binder' to spin up a session where ffmpeg is installed in the backing environment. pydub needs ffmpeg or equivalent.
You can run the following line in a notebook and then open the notebook that it gets to work though that demonstration:
!curl -OL https://gist.githubusercontent.com/fomightez/86482965bbce4bbbb7adb4c98f6cd9e6/raw/d31473699d8a2ec6d31dbf1d9590b8a0ef8972db/pydub_edit_plays_via_mybinder.ipynb```
Or step through the equivalent demonstration code in a notebook in JupyterLan by following these steps.
First enter in a cell the following:
```python
%pip install pydub
Get an audio file to use for testing by running this:
!curl -OL http://www.nch.com.au/acm/8k16bitpcm.wav
Edit that file and playback the result in the notebook without interacting with it, by running this in a cell:
from pydub import AudioSegment
from pydub.playback import play
start = 1000
end = 3000
audio = AudioSegment.from_file("8k16bitpcm.wav")
audio_piece = audio[start:end]
audio_piece.export("test_clip.wav", format='wav')
from IPython.display import Audio, display
Audio("test_clip.wav", autoplay=True)
I am using Jupyter on VS code, the graphs work fine when views on VS code, however when I upload the ipynb file on GitHub none of the graphs show up
Code:
import plotly.express as px
countryc = px.histogram(country_count , "Country" , color='type').update_xaxes(categoryorder = "total descending")
countryc.show()
I tried saving the the graph as an html file using :
countryc.write_html('/Python/Netflix EDA/countryc.html')
HTML(filename='/Python/Netflix EDA/countryc.html')
IFrame(src='/Python/Netflix EDA/countryc.html', width = 1300, height=700)
however I am still unable display this file when viewing on GitHub. Any suggestion on how to show the interactive files on GitHub?
Is it possible for a Python script to write into a iPython Notebook?
with open("my_notebook.ipynb", "w") as jup:
jup.write("print(\"Hello there!\")")
If there's some package for doing so, can I also control the way cells are split in the notebook?
I'm designing a software tool (that carries out some optimization) to prepare an iPython notebook that can be run on some server performing scientific computations.
I understand that a related solution is to output to a Python script and load it within a iPython Notebook using %load my_python_script.py. However, that involves a user to type stuff that I would ideally like to avoid.
Look at the nbformat repo on Github. The reference implementation is shown there.
From their docs
Jupyter (né IPython) notebook files are simple JSON documents, containing text, source code, rich media output, and metadata. Each segment of the document is stored in a cell.
It also sounds like you want to create the notebook programmatically, so you should use the NotebookNode object.
For the code, something like, should get you what you need. new_cell_code should be used if you have code cells versus just plain text cells. Text cells should use the existing markdown formatting.
import nbformat
notebook = nbformat.v4.new_notebook()
text = """Hello There """
notebook['cells'] = [nbformat.v4.new_markdown_cell(text)]
notebook= nbformat.v4.new_notebook()
nbformat.write(notebook,'filename.ipynb')
I've a quick question about "pandas_profiling" .So basically i'm trying to use the pandas 'profiling' but instead of showing the output it says something like this:
<pandas_profiling.ProfileReport at 0x23c02ed77b8>
Where i'm making the mistake?? or Does it have anything to do with Ipython?? Because i'm using Ipython in Anaconda.
try this
pfr = pandas_profiling.ProfileReport(df)
pfr.to_notebook_iframe()
pandas_profiling creates an object that then needs to be displayed or output. One standard way of doing so is to save it as an HTML:
profile.to_file(outputfile="sample_file_name.html")
("profile" being the variable you used to save the profile itself)
It doesn't have to do with ipython specifically - the difference is that because you're going line by line (instead of running a full block of code, including the reporting step) it's showing you the object itself. The code above should allow you to see the report once you open it up.
I am using altair on a jupyter notebook where I am trying to convert a pandas dataframe to a json file before passing it to Altair chart. I would like to save the final chart as a html file.
import altair as alt
alt.renderers.enable('notebook')
alt.data_transformers.enable('json')
from vega_datasets import data
url = 'data.json'
cars = data.cars()
cars.to_json(url, orient='records')
charts1=alt.Chart(url).mark_circle(size=60).encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color='Cylinders:O',
tooltip=['Name:Q', 'Origin:N', 'Horsepower:Q', 'Miles_per_Gallon:Q']
).interactive()
charts1.save('cars1.html')
charts2=alt.Chart(cars).mark_circle(size=60).encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color='Cylinders:O',
tooltip=['Name:Q', 'Origin:N', 'Horsepower:Q', 'Miles_per_Gallon:Q']
).interactive()
charts2.save('cars2.html')
charts1 | charts2
Both charts1 and charts2 are displayed correctly in jupyter notebook but only cars2.html is displayed properly when I open it in my browser. cars1.html is just an empty white box. Have I got the syntax wrong? I am in python3.6, Altair version: '2.2.2', Jupyter: '4.3.0'.
For chart1, the data exists in a separate file (data.json), and that file has to be accessible to the browser in order for the browser to render the data in a chart. If the data file is not accessible (either because it is at the wrong URL, or due to a cross-origin issue) then the result will be a blank chart.
To determine what the issue is, open your browser's javascript console and check what the error is.
For example, if you're viewing your chart from a file:// URL, the data may not be accessible if your browser has strict cross-origin policies. Try viewing the file via a local webserver instead (you can use python -m http.server).