Adding Plotly Charts to Markdown

Fri, Apr 16, 2021 5-minute read

Quick reference that shows options to add plotly charts to a markdown document.

Add raw html output to markdown

Thanks to this article from http://www.kellieottoboni.com - I updated the syntax to use the latest version of plotly because you don’t have to fiddle with plotly offline versions anymore.

Steps:

Create a Plotly figure object:

# From https://plotly.com/python/line-charts/
import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color='country')
fig.show()

Get HTML from the figure object

Then you want to get the raw html using either the to_html() method or the write_html method, with some flags that should honestly be default:

# Output html that you can copy paste
fig.to_html(full_html=False, include_plotlyjs='cdn')  
# Saves a html doc that you can copy paste
fig.write_html("output.html", full_html=False, include_plotlyjs='cdn')

These two flags prevent it from creating a huge html document and from including 3MB of the plotly javascript stuff - total overkill.

Copy and paste directly into your markdown

Here’s the output, copied and pasted into a markdown document (powered by Jekyll/Minimal Mistakes):

Tested on Plotly 4.14.3

Reference:

  1. Inspiration from http://www.kellieottoboni.com
  2. Plotly Documentation with additional details on html output