Can I use matplotlib in Dynamo?

Thank you

import sys
import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
dirAppLoc = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) 
sys.path.append(dirAppLoc + r'\python-3.8.3-embed-amd64\Lib\site-packages')

clr.AddReference('System.Drawing')
import System.Drawing
from System.Drawing import *
from System.Drawing.Imaging import *
from System.IO import MemoryStream

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import io
import math

def plt2arr(fig):
    """
    need to draw if figure is not drawn yet
    """
    fig.canvas.draw()
    rgba_buf = fig.canvas.buffer_rgba()
    (w,h) = fig.canvas.get_width_height()
    rgba_arr = np.frombuffer(rgba_buf, dtype=np.uint8).reshape((h,w,4))
    return rgba_arr

def convertToBitmap2(npImgArray):
    bitmap_ = None
    # remove alpha
    if npImgArray.ndim == 3 and npImgArray.shape[-1] == 4:
        npImgArray = npImgArray[:, :, :-1]
    # convert to PIL Image
    if npImgArray.ndim == 3:
        image = Image.fromarray(npImgArray, "RGB")
    else:
        image = Image.fromarray(npImgArray, "L")
    # convert to Python ByteArray
    byteIO = io.BytesIO()
    image.save(byteIO, format='BMP')
    byteArr = byteIO.getvalue()
    # convert to Net ByteArray
    netBytes = System.Array[System.Byte](byteArr)
    with MemoryStream(netBytes) as ms:
        bitmap_ = Bitmap(ms)
    return bitmap_

#///////////////////////////////////////////////////////


def koch_snowflake(order, scale=10):
    """
    Return two lists x, y of point coordinates of the Koch snowflake.

    Parameters
    ----------
    order : int
        The recursion depth.
    scale : float
        The extent of the snowflake (edge length of the base triangle).
    """
    def _koch_snowflake_complex(order):
        if order == 0:
            # initial triangle
            angles = np.array([0, 120, 240]) + 90
            return scale / np.sqrt(3) * np.exp(np.deg2rad(angles) * 1j)
        else:
            ZR = 0.5 - 0.5j * np.sqrt(3) / 3

            p1 = _koch_snowflake_complex(order - 1)  # start points
            p2 = np.roll(p1, shift=-1)  # end points
            dp = p2 - p1  # connection vectors

            new_points = np.empty(len(p1) * 4, dtype=np.complex128)
            new_points[::4] = p1
            new_points[1::4] = p1 + dp / 3
            new_points[2::4] = p1 + dp * ZR
            new_points[3::4] = p1 + dp / 3 * 2
            return new_points

    points = _koch_snowflake_complex(order)
    x, y = points.real, points.imag
    return x, y
    
x, y = koch_snowflake(order=IN[0])

fig, (ax1, ax2, ax3, ax4 ) = plt.subplots(1, 4, figsize=(9,3),
                                    subplot_kw={'aspect': 'equal'})
ax1.fill(x, y, facecolor='none', edgecolor='blue', linewidth=3)
ax2.fill(x, y, facecolor='none', edgecolor='orangered', linewidth=3)
ax3.fill(x, y, facecolor='none', edgecolor='purple', linewidth=3)
ax4.fill(x, y, facecolor='none', edgecolor='gray', linewidth=3)

fig.suptitle('Happy new year', fontsize=IN[2], fontweight='bold', color='blue')

s = IN[1]

t1 = ax1.text(
    0, 0, "2", ha="center", va="center", rotation=0, size=s,
    bbox=dict(boxstyle="round,pad=0.1", fc="cyan", ec="b", lw=2))
t2 = ax2.text(
    0, 0, "0", ha="center", va="center", rotation=0, size=s,
    bbox=dict(boxstyle="round,pad=0.1", fc="cyan", ec="b", lw=2))
t3 = ax3.text(
    0, 0, "2", ha="center", va="center", rotation=0, size=s,
    bbox=dict(boxstyle="round,pad=0.1", fc="cyan", ec="b", lw=2))
t4 = ax4.text(
    0, 0, "3", ha="center", va="center", rotation=0, size=s,
    bbox=dict(boxstyle="round,pad=0.1", fc="cyan", ec="b", lw=2))


image_from_plot = plt2arr(fig)
bitmap1 = convertToBitmap2(image_from_plot)

OUT = bitmap1

5 Likes