Use tempdir to save save SVG output file unless users explicitly set the saving location
Closed this issue · 1 comments
jooyoungseo commented
Currently, we have a default directory to save the SVG output file. However, this is not an ideal solution. Save an SVG to
OS temp directory (AKA, tempdir) by default and open the HTML file in users' default browser when it is written.
Also, consider adding a parameter for users to pass path/to/file if they would like to explicitly set the saving location.
jooyoungseo commented
@Ankita-Khiratkar -- The following includes useful hints:
import seaborn as sns
import matplotlib.pyplot as plt
import io
import tempfile
import os
import webbrowser
# Assuming you have a dataset named df
sns.set_theme(style="whitegrid")
ax = sns.boxplot(x=df["your_column_name"])
# Create an io.BytesIO object and save the seaborn plot as SVG to it
svg_file = io.BytesIO()
plt.savefig(svg_file, format='svg', bbox_inches='tight')
plt.close()
# Seek to the beginning of the file and read it into a variable
svg_file.seek(0)
svg_data = svg_file.read().decode('utf-8')
# Now you can include svg_data in your HTML. Remember, svg_data is a string containing XML/SVG data.
html_template = f"""
<html>
<head>
<title>Your Page</title>
</head>
<body>
{svg_data}
</body>
</html>
"""
# Save the HTML string to a file in the temp directory
temp_dir = tempfile.gettempdir()
html_file_path = os.path.join(temp_dir, 'my_plot.html')
with open(html_file_path, 'w') as f:
f.write(html_template)
print(f'HTML file saved at: {html_file_path}')
# Open in the default web browser
webbrowser.open('file://' + os.path.realpath(html_file_path))