Skip to main content
Version: Python

How to use Matplotlib and Seaborn

This guide shows you how to use Matplotlib and its relative Seaborn to create plots.

By default, Deephaven does not come with Matplotlib or Seaborn, so you can either access the specific Matplotlib Deephaven example or extend the Deephaven Dockerized set up. Both options are documented below.

Quickstart

To get up and running with Matplotlib and Seaborn, clone the Matplotlib Deephaven base repo, enter its directory, and then run docker-compose up -d as usual:

git clone https://github.com/deephaven-examples/deephaven-matplotlib-base.git
cd deephaven-matplotlib-base
docker-compose pull
docker-compose up --build -d

This starts the Deephaven IDE with all the needed packages.

Now, you're ready to use these plotting libraries. Open the IDE to try our sample queries.

Extend Deephaven

If instead you wish to extend the Deephaven build, you can follow the Launch Deephaven from pre-built images steps from the Quickstart guide.

To launch the IDE in a Python session, run:

compose_file=https://raw.githubusercontent.com/deephaven/deephaven-core/main/containers/python-examples/base/docker-compose.yml
curl -O "${compose_file}"

Once you have the docker-compose.yml file pulled down, define your own web Docker image in web/Dockerfile that includes the plug-ins you would like to use. In this case, we are installing Matplotlib.

  1. Create subdirectory web in the same folder as your docker-compose.yml: mkdir web

  2. Create the Dockerfile for web and open for editing: vi web/Dockerfile

  3. Paste the following into the web/Dockerfile and save:

    # Pull the web-plugin-packager image
    FROM ghcr.io/deephaven/web-plugin-packager:main as build

    # Specify the plugins you wish to use. You can specify multiple plugins separated by a space, and optionally include the version number, e.g.
    # RUN ./pack-plugins.sh <js-plugin-name>[@version] ...
    # For a list of published plugins, see https://www.npmjs.com/search?q=keywords%3Adeephaven-js-plugin

    # Here is how you would install the matplotlib and table-example plugins
    RUN ./pack-plugins.sh @deephaven/js-plugin-matplotlib @deephaven/js-plugin-table-example

    # Copy the packaged plugins over
    FROM ghcr.io/deephaven/web:${VERSION:-latest}
    COPY --from=build js-plugins/ /usr/share/nginx/html/js-plugins/

Many plug-ins will also require a server side component. To define the plug-ins used on the server, create a server/Dockerfile similar to above:

  1. Create subdirectory server in the same folder as your docker-compose.yml: mkdir server

  2. Create the Dockerfile for server and open for editing: vi server/Dockerfile

  3. Paste the following into the server/Dockerfile and save:

    FROM ghcr.io/deephaven/server:${VERSION:-latest}
    # pip install any of the plugins required on the server
    RUN pip install deephaven-plugin-matplotlib

After building, you need to specify using that build in your docker-compose. Do this by modifying the existing docker-compose.yml file and replace the web and server definitions with the following:

services:
server:
# Comment out the image name
# image: ghcr.io/deephaven/server:${VERSION:-latest}
# Build from your local Dockerfile you just created
build: ./server

...

web:
# Comment out the image name
# image: ghcr.io/deephaven/web:${VERSION:-latest}
# Build from your local Dockerfile you just created
build: ./web

When you're done, your directory structure should look like:

.
├── docker-compose.yml
├── server
│ └── Dockerfile
└── web
└── Dockerfile

Everything's ready to go! Now after running docker-compose up as normal, you can use your custom image with your JS plug-ins installed. See what you can create!

Matplotlib examples

Here is the basic usage of Matplotlib to show one figure:

import matplotlib.pyplot as plt


x = [0, 2, 4, 6]
y = [1, 3, 4, 8]
plt.figure()
plt.plot(x, y)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('plotted x and y values')
plt.legend(['line 1'])

m_figure=plt.gcf()

img

The full functionaly of Matplotlib is avilable inside the Deephaven IDE:

import matplotlib.pyplot as plt
import numpy as np
import math

# Get the angles from 0 to 2 pie (360 degree) in narray object
X = np.arange(0, math.pi*2, 0.05)

# Using built-in trigonometric function we can directly plot
# the given cosine wave for the given angles
Y1 = np.sin(X)
Y2 = np.cos(X)
Y3 = np.tan(X)
Y4 = np.tanh(X)

# Initialise the subplot function using number of rows and columns
figure, axis = plt.subplots(2, 2)

# For Sine Function
axis[0, 0].plot(X, Y1)
axis[0, 0].set_title("Sine Function")

# For Cosine Function
axis[0, 1].plot(X, Y2)
axis[0, 1].set_title("Cosine Function")

# For Tangent Function
axis[1, 0].plot(X, Y3)
axis[1, 0].set_title("Tangent Function")

# For Tanh Function
axis[1, 1].plot(X, Y4)
axis[1, 1].set_title("Tanh Function")

img

Here are some 3D examples from Rashida Nasrin Sucky. The data, available from Kaggle, needs to be placed in the data directory. For more information see our guide on Docker data volumes.

import pandas as pd
import numpy as np
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
df = pd.read_csv("/data/auto_clean.csv")


fig = plt.figure(figsize=(10, 10))
ax = plt.axes(projection="3d")
ax.scatter3D(df['length'], df['width'], df['height'],
c = df['peak-rpm'], s = df['price']/50, alpha = 0.4)
ax.set_xlabel("Length")
ax.set_ylabel("Width")
ax.set_zlabel("Height")
ax.set_title("Relationship between height, weight, and length")
plt.show()

img

df['body-style'].unique()

df['body_style1'] = df['body-style'].replace({"convertible": 1,
"hatchback": 2,
"sedan": 3,
"wagon": 4,
"hardtop": 5})

gr = df.groupby("body_style1")['peak-rpm', 'price'].agg('mean')
x = gr.index
y = gr['peak-rpm']
z = [0]*5
colors = ["b", "g", "crimson", 'r', 'pink']
dx = 0.3 * np.ones_like(z)
dy = [30]*5
dz = gr['price']
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection="3d")
ax.set_xticklabels(['convertible', 'hatchback', 'sedan', 'wagon', 'hardtop'])
ax.set_xlabel("Body Style", labelpad = 7)
ax.set_yticks(np.linspace(5000, 5250, 6))
ax.set_ylabel("Peak Rpm", labelpad=10)
ax.set_zlabel("Price")
ax.set_zticks(np.linspace(7000, 22250, 6))
ax.set_title("Change of Price with Body_style and Peak RPM")
ax.bar3d(x, y, z, dx, dy, dz)

img

def z_function(x, y):
return np.sin(np.sqrt(x**2 + y**2))
plt.figure(figsize=(8, 8))
ax = plt.axes(projection="3d")
x = df['peak-rpm']
y = df['city-mpg']
z = z_function(x, y)
ax.plot_trisurf(x, y, z,
cmap='viridis', edgecolor='none');
ax.set_xlabel("Peak RPM")
ax.set_ylabel("City-MPG")
ax.set_title("Peak RPM vs City-MPG")
ax.view_init(60, 25)
plt.show()

tri_surf=plt.gcf()

img

Seaborn examples

Here is the basic usage of Seaborn:

import os
os.system("pip install seaborn")

import seaborn as sns
df = sns.load_dataset("penguins")
plt.figure()
sns.pairplot(df, hue="species")
myFig2 = plt.gcf()

img