|
| 1 | +import base64 |
| 2 | + |
| 3 | +# Shap plots internally call plt.show() |
| 4 | +# On Linux, prevent plt.show() from emitting a non-GUI backend warning. |
| 5 | +import os |
| 6 | +from io import BytesIO |
| 7 | + |
| 8 | +import matplotlib.pyplot as plt |
| 9 | +import shap |
| 10 | +import streamlit.components.v1 as components |
| 11 | +from matplotlib.figure import Figure |
| 12 | + |
| 13 | +os.environ.pop("DISPLAY", None) |
| 14 | +# Text plots return a IPython.core.display.HTML object |
| 15 | +# Set diplay=False to return HTML string instead |
| 16 | +shap.plots.text.__defaults__ = (0, 0.01, "", None, None, None, False) |
| 17 | +# Prevent clipping of the ticks and axis labels |
| 18 | +plt.rcParams["figure.autolayout"] = True |
| 19 | + |
| 20 | +# Note: Colorbar changes (introduced bugs) in matplotlib>3.4.3 |
| 21 | +# cause the colorbar of certain shap plots (e.g. beeswarm) to not display properly |
| 22 | +# See: https://github.com/matplotlib/matplotlib/issues/22625 and |
| 23 | +# https://github.com/matplotlib/matplotlib/issues/22087 |
| 24 | +# If colorbars are not displayed properly, try downgrading matplotlib to 3.4.3 |
| 25 | + |
| 26 | + |
| 27 | +def st_shap(plot, height=None, width=None): |
| 28 | + """Takes a SHAP plot as input, and returns a streamlit.delta_generator.DeltaGenerator as output. |
| 29 | +
|
| 30 | + It is recommended to set the height and width |
| 31 | + parameter to have the plot fit to the window. |
| 32 | +
|
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + plot : None or matplotlib.figure.Figure or SHAP plot object |
| 36 | + The SHAP plot object. |
| 37 | + height: int or None |
| 38 | + The height of the plot in pixels. |
| 39 | + width: int or None |
| 40 | + The width of the plot in pixels. |
| 41 | +
|
| 42 | + Returns |
| 43 | + ------- |
| 44 | + streamlit.delta_generator.DeltaGenerator |
| 45 | + A SHAP plot as a streamlit.delta_generator.DeltaGenerator object. |
| 46 | + """ |
| 47 | + |
| 48 | + # Plots such as waterfall and bar have no return value |
| 49 | + # They create a new figure and call plt.show() |
| 50 | + if plot is None: |
| 51 | + # Test whether there is currently a Figure on the pyplot figure stack |
| 52 | + # A Figure exists if the shap plot called plt.show() |
| 53 | + if plt.get_fignums(): |
| 54 | + fig = plt.gcf() |
| 55 | + ax = plt.gca() |
| 56 | + |
| 57 | + # Save it to a temporary buffer |
| 58 | + buf = BytesIO() |
| 59 | + |
| 60 | + if height is None: |
| 61 | + _, height = fig.get_size_inches() * fig.dpi |
| 62 | + |
| 63 | + if width is None: |
| 64 | + width, _ = fig.get_size_inches() * fig.dpi |
| 65 | + |
| 66 | + fig.set_size_inches(width / fig.dpi, height / fig.dpi, forward=True) |
| 67 | + fig.savefig(buf, format="png") |
| 68 | + |
| 69 | + # Embed the result in the HTML output |
| 70 | + data = base64.b64encode(buf.getbuffer()).decode("ascii") |
| 71 | + html_str = f"<img src='data:image/png;base64,{data}'/>" |
| 72 | + |
| 73 | + # Enable pyplot to properly clean up the memory |
| 74 | + plt.cla() |
| 75 | + plt.close(fig) |
| 76 | + |
| 77 | + fig = components.html(html_str, height=height, width=width) |
| 78 | + else: |
| 79 | + fig = components.html( |
| 80 | + "<p>[Error] No plot to display. Received object of type <class 'NoneType'>.</p>" |
| 81 | + ) |
| 82 | + |
| 83 | + # SHAP plots return a matplotlib.figure.Figure object when passed show=False as an argument |
| 84 | + elif isinstance(plot, Figure): |
| 85 | + fig = plot |
| 86 | + |
| 87 | + # Save it to a temporary buffer |
| 88 | + buf = BytesIO() |
| 89 | + |
| 90 | + if height is None: |
| 91 | + _, height = fig.get_size_inches() * fig.dpi |
| 92 | + |
| 93 | + if width is None: |
| 94 | + width, _ = fig.get_size_inches() * fig.dpi |
| 95 | + |
| 96 | + fig.set_size_inches(width / fig.dpi, height / fig.dpi, forward=True) |
| 97 | + fig.savefig(buf, format="png") |
| 98 | + |
| 99 | + # Embed the result in the HTML output |
| 100 | + data = base64.b64encode(buf.getbuffer()).decode("ascii") |
| 101 | + html_str = f"<img src='data:image/png;base64,{data}'/>" |
| 102 | + |
| 103 | + # Enable pyplot to properly clean up the memory |
| 104 | + plt.cla() |
| 105 | + plt.close(fig) |
| 106 | + |
| 107 | + fig = components.html(html_str, height=height, width=width) |
| 108 | + |
| 109 | + # SHAP plots containing JS/HTML have one or more of the following callable attributes |
| 110 | + elif hasattr(plot, "html") or hasattr(plot, "data") or hasattr(plot, "matplotlib"): |
| 111 | + shap_js = f"{shap.getjs()}".replace("height=350", f"height={height}").replace( |
| 112 | + "width=100", f"width={width}" |
| 113 | + ) |
| 114 | + shap_html = f"<head>{shap_js}</head><body>{plot.html()}</body>" |
| 115 | + fig = components.html(shap_html, height=height, width=width) |
| 116 | + |
| 117 | + # shap.plots.text plots have been overridden to return a string |
| 118 | + elif isinstance(plot, str): |
| 119 | + fig = components.html(plot, height=height, width=width, scrolling=True) |
| 120 | + |
| 121 | + else: |
| 122 | + fig = components.html( |
| 123 | + "<p>[Error] No plot to display. Unable to understand input.</p>" |
| 124 | + ) |
| 125 | + |
| 126 | + return fig |
0 commit comments