This is a Datapane import of the original Medium post, which can be found here
Have you ever wanted to share your interactive Python chart on social media platforms such as Medium, Reddit, or your own blog but ended up having to take photos or record videos or gifs of the charts? Alternatively, many people end up using a non-code solution, like Mapbox or Flourish, even though they'd rather build their visualisations in Python using libraries like Pandas, Altair, Bokeh, Folium, and Plotly.
After experiencing this pain-point first-hand, we decided to try and make it easy for you to embed your interactive chart in social platforms in two lines of code.
Let’s say you created an interactive Plotly bubble chart with this code:
import plotly.express as px df = px.data.gapminder() fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60) fig.show()
Using Datapane's API, you can publish this Plotly chart to the web and embed it into Medium.
Firstly, install Datapane using pip:
pip3 install datapane
Next, you will need to create an account on the public Datapane server, which will allow you to host your visualisations on the web. To do this, sign-up to Datapane to get your API token. Copy this, and then use it to login through the datapane CLI:
datapane login --token=[your_secret_token]
Once you have logged in, you can use the Datapane API to publish your plots. Import Datapane into your script, and publish a new
Report with a single
Plot component in it. In the following example, we are also telling Datapane to set the visibility of our report to public, so anyone will the URL will be able to access it.
import plotly.express as px import datapane as dp df = px.data.gapminder() fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60) dp.Report( dp.Plot(fig) ).publish(name='my_plot', open=True, visibility='PUBLIC')
When you run this Python code, Datapane will upload your Plotly chart using the API and give you a URL which you can share.
Next, copy this link into your Medium post in Edit Mode, and and - voila! - an embedded chart is automatically created for you inside your Medium post.
Because you're in Edit Mode on Medium, you will first see your chart without its interactive mode, but as soon as you publish your article, you (and your readers) will be able to use it interactively.
For an example of a Medium post with some embeds, check out this post.