Published on

Adding Plotly Charts to Markdown

Authors
  • avatar
    Name
    Nelson Tang
    Twitter

Quick reference that shows options to add plotly charts to a markdown document. This assumes that your markdown interpreter can handle raw html (like Jekyll or Hugo).

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:

1. 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()

2. 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:

  • include_plotlyjs='cdn'
  • full_html=False

helps you avoid creating a huge html document and from including 3MB of the plotly javascript stuff - total overkill.

3. Copy and paste directly into your markdown

Note: I've since migrated my blog from Jekyll and Hugo to this new site powered by Next.js and MDX which requires some extra work to make this work.

  • Jekyll: When I was using Jekyll, I could paste in the raw html directly into markdown and it would parse it.
  • Hugo: Check your Hugo template, but you'll need to use or make a shortcode for raw html, like this example from "Make with Hugo":

Here's the output, copied and pasted into a markdown document

img

Tested on Plotly 4.14.3

Reference:

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