Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created August 28, 2024 03:59
Show Gist options
  • Save hyrious/6e50cb12d689917366fc3aad15b59b0e to your computer and use it in GitHub Desktop.
Save hyrious/6e50cb12d689917366fc3aad15b59b0e to your computer and use it in GitHub Desktop.
Custom matplotlib and plotly.py's fig.show()
"""matplotlib.use('module://matplotlib_custom'), remember to add this file to PYTHONPATH"""
from matplotlib.backend_bases import Gcf
from matplotlib.backends.backend_agg import FigureCanvasAgg
FigureCanvas = FigureCanvasAgg
def show(*args, **kwargs):
var = globals().get('custom')
if var:
context = var.get('context')
for figmanager in Gcf.get_all_fig_managers():
buffer = BytesIO()
figmanager.canvas.figure.savefig(buffer, format='png')
buffer.seek(0)
png = buffer.getvalue()
buffer.close()
url = f'data:image/png;base64,{b64encode(png).decode('utf-8')}'
payload = { "type": "image", "data": url }
context.preview(payload)
else:
print('matplotlib_custom: no globals().get("custom")', file=sys.stderr)
from plotly.io import renderers
from plotly.io.base_renderers import ExternalRenderer
class CustomRenderer(ExternalRenderer):
def render(self, fig_dict):
from plotly.io import to_html
html = to_html(
fig_dict,
include_plotlyjs=True,
include_mathjax="cdn",
full_html=True,
default_width="100%",
default_height="100%",
validate=False,
)
globals().get('custom').get('context').html(html)
renderers['custom'] = CustomRenderer()
renderers.default = 'custom'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment