AnswerDotAI / FastHTML-Gallery

https://gallery.fastht.ml/
65 stars 10 forks source link

matplotlib svg #36

Open Isaac-Flath opened 3 months ago

Isaac-Flath commented 3 months ago

Discord message: https://discord.com/channels/689892369998676007/1247700012952191049/1276592777823653979


Inspired by fh-matplotlib, I wrote a decorator for matplotlib svg, which gives better resolution as it uses vector graph. Here's the code:

def fh_svg(func):
    "svg to fasthtml item"
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)

        f = io.StringIO()
        plt.savefig(f, format='svg', bbox_inches='tight')

        f.seek(0)
        svg_data = f.getvalue()
        plt.close()

        return NotStr(svg_data)
    return wrapper

To use:

@fh_svg
def matplotlib_plot():
    plt.plot(np.arange(25), np.random.exponential(1, size=25))

# to display in fasthtml
Div(matplotlib_plot())    
Isaac-Flath commented 3 months ago
sky1ove commented 3 months ago

credit to Lily Cai