Skip to content

Multiplot: create new simpler strategy for saving single images with multiple plots #3948

@swharden

Description

@swharden

I made this today and it's a helpful start.

Features could be added to help with complex layouts (arbitrary sizes, multi-column plots, etc) as well as tools to facilitate data area alignment and axis limit matching.

Usage

Multiplot mp = new(600, 400);
mp.AddColumn(plots[0], 0, 2);
mp.AddColumn(plots[1], 1, 2);
mp.SavePng("multi.png");

Implementation

using ScottPlot;
using SkiaSharp;

namespace AbfAuto.Core;

public class Multiplot
{
    public int Width { get; }
    public int Height { get; }

    readonly SKSurface Surface;
    SKCanvas Canvas => Surface.Canvas;

    public Multiplot(int width, int height)
    {
        SKImageInfo imageInfo = new(width, height, SKColorType.Rgba8888, SKAlphaType.Premul);
        Width = width;
        Height = height;
        Surface = SKSurface.Create(imageInfo);
    }

    public void AddColumn(Plot plot, int columnIndex, int totalColumns)
    {
        PixelSize size = new(Width / totalColumns, Height);
        Pixel corner = new(size.Width * columnIndex, 0);
        PixelRect pxRect = new(corner, size);
        Console.WriteLine(pxRect);
        plot.RenderManager.ClearCanvasBeforeEachRender = false;
        plot.Render(Canvas, pxRect);
    }

    public void SavePng(string path)
    {
        using SKImage skImage = Surface.Snapshot();
        ImageFormat format = ImageFormat.Png;
        SKEncodedImageFormat skFormat = format.ToSKFormat();
        using SKData data = skImage.Encode(skFormat, 100);
        byte[] bytes = data.ToArray();
        File.WriteAllBytes(path, bytes);
    }
}

Output

image

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions