Lesson 5
Wrapping and Gifting Your Plot
Topic Overview

Hello and welcome to the lesson on "Wrapping and Gifting Your Plot". Today, we'll learn how to create polished visualizations using Plotly Graph Objects, focusing on exporting it in various formats. By the end of this lesson, you'll be able to present your data graphically in a way that both informs and engages, making your digital storytelling more compelling.

Building the Visualization: Scatter Plot with Custom Markers

Now, let's remind ourselves what the scatter plot looks like.

Python
1import plotly.graph_objects as go 2 3# Create figure 4fig = go.Figure() 5 6# Add scatter trace 7fig.add_trace( 8 go.Scatter( 9 x=df['weekid'], 10 y=df['week_position'], 11 mode='markers', 12 marker=dict( 13 size=df['weeks_on_chart'], 14 sizemode='area', 15 sizeref=2 * max(df['weeks_on_chart']) / (40 ** 2), 16 color=df['peak_position'], 17 colorscale='RdYlGn_r', 18 colorbar=dict(title='Peak Position')), 19 text=[f"Song: {song}<br>Performer: {performer}" 20 for song, performer in zip(df['song'], df['performer'])], 21 hovertemplate="%{text}<br>" 22 "Date: %{x}<br>" + 23 "Position: %{y}<br>" + 24 "Weeks on Chart: %{marker.size}<br>" + 25 "<extra></extra>" 26 ) 27) 28 29# Update layout 30fig.update_layout( 31 title='Song Performance Matrix', 32 xaxis_title='Date', 33 yaxis_title='Chart Position', 34 yaxis=dict( 35 autorange="reversed", 36 gridcolor='lightgray', 37 ), 38 xaxis=dict(gridcolor='lightgray'), 39 plot_bgcolor='white', 40 hoverlabel=dict( 41 bgcolor="white", 42 font_size=12, 43 ) 44)

In this plot, we use various marker properties to convey additional information, such as size to indicate weeks_on_chart and color to represent peak_position. These customizations enrich the plot by visualizing complex data points in a straightforward manner.

Customizing layout properties like axis titles, direction, and background colors can significantly impact readability and visual balance, ensuring your audience focuses on the insights.

Exporting the Masterpiece: Saving and Sharing image files

Now, let's save our work in different formats to suit various purposes. The write_image method from Plotly allows for exporting your visualization into multiple image formats.

Python
1# Save as different Image formats 2fig.write_image("static_chart.svg") # SVG format 3fig.write_image("static_chart.pdf") # PDF format 4fig.write_image( 5 "custom_size_chart.jpg", # JPG format 6 width=1200, 7 height=800, 8 scale=2 9)

Here's how the parameters work:

  • "static_chart.svg": Specifies the file name and format for saving. Here, it's saved as a Scalable Vector Graphics (SVG) file, which is ideal for high-quality scalable images.
  • "static_chart.pdf": By changing the file extension, you can export your plot as a PDF document.
  • "custom_size_chart.jpg": Exports the plot as a JPG image. Alongside, there's customization by adding width=1200 and height=800, defining the image dimensions for higher resolution.
  • scale=2: This parameter enhances the resolution of the JPG image by scaling its dimensions by the provided factor, ensuring clearer images, especially useful for printing purposes.
Exporting your data using JSON

The JSON format is a versatile option for saving your visualizations, which enables easy sharing and reusability of the plot's data and layout. Here's a detailed look at the code:

Python
1# Save as JSON data 2fig_json = fig.to_json() 3with open('chart_data.json', 'w') as f: 4 f.write(fig_json) 5 6# Load from JSON data 7with open('chart_data.json', 'r') as f: 8 fig_json = f.read() 9 10# Convert JSON to Figure object 11fig = go.Figure(json.loads(fig_json))
  • fig.to_json(): This method converts the current Figure object into a JSON string, effectively capturing all the data and layout configurations of the plot.
  • fig = go.Figure(json.loads(fig_json)): Here, the JSON string is parsed back into a dictionary using json.loads(fig_json), and then it's passed to go.Figure to recreate the original plot. This step effectively regenerates the plot from the saved JSON data, preserving its structure and properties.

This JSON-based approach is particularly useful when you need to save the visualization for future modifications, share it with collaborators, or export it to another environment for further processing.

Save to HTML

The HTML format is a powerful option for exporting interactive plots, allowing you to easily share or embed them into web pages. Here's an explanation of the code:

Python
1fig.write_html( 2 'templates/chart.html', 3 include_plotlyjs="cdn", 4 full_html=True 5)
  • fig.write_html('templates/chart.html'): This method saves the figure as an HTML file in the specified path, in this case, templates/chart.html. The resulting file can be viewed in any web browser, offering an interactive experience of the plot.
  • include_plotlyjs="cdn": By setting this parameter, the Plotly JavaScript library is linked via a Content Delivery Network (CDN) rather than embedding it directly in the HTML file. This approach significantly reduces the file size and ensures the latest version of Plotly.js is used when the plot is displayed.
  • full_html=True: This parameter specifies that the HTML file should include a complete HTML document structure (DOCTYPE, HTML, HEAD, and BODY tags). It makes the file standalone, ready for direct upload or sharing without requiring any additional HTML context. Setting this to False is useful when you want a small snippet of HTML to embed in another document.

This method is an excellent choice for sharing interactive plots, as they maintain the hover, zoom, and pan capabilities of Plotly visualizations, making your data presentations more dynamic and engaging.

Lesson Summary

Congratulations! You've learned how to finalize a data visualization by exporting to different formats. You've not only crafted an interactive plot with Plotly but also explored how to customize every aspect for maximum impact and shared it in various formats. The skills you've gained today will serve you well in making your data presentations more effective and engaging. Now it's time to practice these techniques and solidify your learning. Let’s wrap your data in visual beauty!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.