Last week, I gave you the shortest explanation of how a graph on a website works. So now you know what HTML, CSS, SVG, and JavaScript are.
95% of you said you're interested in how the web works, so today I want to take it one step further and answer this question:
➡️ Can I make interactive graphs with R or Python, and how does it work?
Short answer: yes.
Both R and Python offer powerful libraries that let you build stunning interactive charts with just a few lines of code.
In R, this family of packages is called HTML widgets. In Python... I'm not sure there's a name for it.
I love HTML widgets.
I couldn't live without plotly. The ggplotly() function turns any ggplot2 chart interactive with just one line!
ggplot + 1 line of code = interactive graph!
There's also ggiraph, which allows finer control and lets you link multiple charts together.
You’ll also find chart-specific packages like leaflet for interactive maps, DT for interactive tables, and dygraphs for time series.
interactive time series with dygraphs
Just invest a couple of minutes and the wow effect is guaranteed next time you show it to your boss.
In Python, it works pretty much the same way. Plotly is available too, along with solid alternatives like Bokeh and Altair. And just like in R, you’ve got chart-type-specific tools like Folium for maps and dash_table for interactive tables.
How does this dark magic work?
I said HTML, CSS, and JS are necessary for interactive graphs. So how can R and Python handle it so easily?
Because all those packages are actually wrappers around JavaScript libraries.
A wrapper is just a function that calls another function behind the scenes.
For example, when you call Chart() in Altair (Python), it builds a JSON description of your chart. That JSON is passed to Vega-Lite, a JavaScript library, which generates the actual HTML and JavaScript that draw the interactive chart in your browser.
🙄 So yes, you're technically writing HTML + CSS + JavaScript. You just don’t realize it! 🔥
How to share it
Since the output is HTML, your graph needs a browser to be viewed.
That has a big impact on how you share it.
You could attach the HTML file to an email... but that would be a shame.
If you’re using GitHub (and if you’re not learning it should be your top priority), your HTML file is already on the web!
You can turn it into a public website and share a URL with your collaborators. Your work will be accessible forever, and you can update it anytime without sending your 1000th email.
This is the main topic of my productive R workflow project, and I will give you some very practical tips about it next week!
See you there!
Yan
PS: Something about the web still confusing or frustrating you? Just hit reply! I read every message. 🫡 PPS: I’m receiving a bunch of awesome testimonials about Matplotlib Journey. Thank you so much! (And don’t forget the course is half-price for groups, academics, and lower-income countries.)