...
/Exploring the Different Ways of Converting Figures
Exploring the Different Ways of Converting Figures
Get familiar with the methods that control the conversion of figures to HTML and images.
The methods that control the conversion of figures start with either to_
or write_
. Let’s explore some of the most interesting ones.
Converting figures into HTML
Plotly figures are actually HTML objects together with the JavaScript that makes them interactive. We can easily capture that HTML file if we want to share it with others via email, for example. We might consider having this as a feature in our dashboards. The users can create the chart or report they want, convert it into HTML, download it, and share it with their colleagues.
All we have to do is provide a file path where we want it to be saved. The method also takes several optional parameters for further customization. Let’s convert our figure into HTML and add a config
option to make it download the figure image in SVG format. The effect of this will be reflected in the HTML file when the camera icon is clicked. The code for this is straightforward:
fig.write_html('html_plot.html',
config={'toImageButtonOptions':
{'format': 'svg'}})
We can now open the file in a browser as a separate HTML file, filling the whole browser screen as shown in the working example below:
Converting figures into images
We have examined the option that allows users to manually download an image of the Figure
object. There is another way of doing so programmatically, which can also be interesting. Just like the write_html
method, we also have a write_image
method. The format of the image can be explicitly provided or inferred from the file extension we provide. We can also set the height
and width
values.
This might be interesting for mass image creation. For example, we might want to create many plots, one for each country, and save each in a file for a separate report on each country. It would be very tedious to do this manually. We might also include this in one of our callbacks for our users. For example, we could allow our users to assemble certain reports and click a button that converts them into images and then downloads them. This code can be run and the output image can be shown in the code widget.
fig.write_image('path/to/image_file.svg',
height=600, width=850)
With this information, we can now get practical and find out more about our dataset.
Plotting using a real dataset
Let’s say we want to create a simple report that shows the user the population of the selected country in the year 2010. This type of report is used when the user knows what they want. That is, they have a specific question about a specific country, metric, and period of ...