Skip to content

matplotlib svg #36

Closed
Closed
@Isaac-Flath

Description

@Isaac-Flath

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())    

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions