Skip to main content

Example Widget Functions

Python

Plot a Plot with Matplotlib

Function Code

import matplotlib.pyplot as plt
import numpy as np
import base64
import io

def handler(event, context):

x = np.random.normal(0, 1, 100)

plt.figure()
plt.plot(x)

#plt.savefig('/tmp/fig.png')
#encoded = base64.b64encode(open('/tmp/fig.png', 'rb').read())
#base64String = encoded.decode('utf-8')

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
base64String = base64.b64encode(buf.read())

return {
"my-image-1": 'data:image/png;base64,' + base64String.decode('utf-8')
}

Elements

This widget has 2 Elements, an Image and an Run Button. The Accessor of the Image is my-image-1

Preview

Clone this Widget

Bitcoin Chart

Function Code

import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import os
import base64
import io

CRYPTOCOMPARE_API_KEY = os.environ['CRYPTOCOMPARE_API_KEY']

def handler(event, context):

response = requests.get('https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=100&api_key=' + CRYPTOCOMPARE_API_KEY)
data = json.loads(response.text)['Data']['Data']

df = pd.DataFrame(data)
df['time'] = df['time'].apply(lambda x: datetime.datetime.fromtimestamp(x))
df = df.set_index('time')
plt.figure()
df['close'].plot()

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
base64String = base64.b64encode(buf.read())

return {
"my-image-1": 'data:image/png;base64,' + base64String.decode('utf-8')
}

Elements

This widget has 2 Elements, an Image and an Run Button. The Accessor of the Image is my-image-1

Preview