-
Notifications
You must be signed in to change notification settings - Fork 3
/
plotting_utils.py
91 lines (77 loc) · 2.7 KB
/
plotting_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import io
import base64
from typing import Union, Tuple
import matplotlib.pyplot as plt
import matplotlib.figure as figure
def print_plot(
plot_obj: Union[plt.Axes, figure.Figure],
width: int = 500,
dpi: int = 100,
download: bool = False,
download_text: str = "Download Plot",
download_file_name: str = "myplot",
) -> Union[str, Tuple[str, str]]:
"""
>>> print_plot(
plot_obj: Union[plt.Axes, figure.Figure],
width: int = 500,
dpi: int = 100,
download: bool = False,
download_text: str = "Download Plot",
download_file_name: str = "myplot"
) -> Union[str, Tuple[str, str]]
Converts a matplotlib plot into an HTML image tag and optionally provides a download link for the image.
Parameters
----------
plot_obj : Union[plt.Axes, figure.Figure]
The matplotlib plot to be converted.
width : int, optional
The width of the image in pixels. (Defaults to 500)
dpi : int, optional
The DPI of the image. (Defaults to 100)
download : bool, optional
If set to True, a download link will be provided. (Defaults to False)
download_text : str, optional
The text to be displayed for the download link. (Defaults to "Download Plot")
download_file_name : str, optional
The name of the downloaded file. (Defaults to 'myplot')
Returns
-------
Union[str, Tuple[str, str]]
If `download` is False, returns the HTML image as a string.
If `download` is True, returns a tuple consisting of the HTML image as a string and the download link as a string.
Examples
----------
**Without Download Link**:
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 2, 3])
>>> plot = msc.print_plot(ax)
>>> return {
"plot": plot
}
**With Download Link and Custom Download Text**:
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 2, 3])
>>> plot, download_link = msc.print_plot(ax, download=True, download_text="Download My Plot")
>>> return {
"plot": plot,
"download_link": download_link
}
"""
if isinstance(plot_obj, plt.Axes):
plot_obj = plot_obj.get_figure()
buffer = io.BytesIO()
plot_obj.savefig(buffer, format="png", dpi=dpi)
if hasattr(plot_obj, "close"):
plot_obj.close()
encoded_image = (
f"data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode()}"
)
html_img = f"<img src='{encoded_image}' width='{width}'>"
if not download:
return html_img
download_link = (
f"<a href='{encoded_image}' "
f"download='{download_file_name}.png'>{download_text}</a>"
)
return html_img, download_link