Kind-pyplot: Displaying Python plots with the Clojure Kindly convention

Kind-pyplot is a small Clojure library for displaying Python plots. It uses the Kindly convention, thus works in Kindly-compatible tools such as Clay.

The implementation is inspired by the Parens for Pyplot tutorial by Carin Meier from Jan 2020.

Source: (GitHub repo)

Artifact: Clojars Project

Discussion

Setup

(ns index
  (:require [scicloj.kind-pyplot.v1.api :as pyplot]))

API

The with-pyplot macro takes Clojure forms that create a plot. It evaluates them and returns an SVG plot. For example:

(pyplot/with-pyplot
  (matplotlib.pyplot/plot
   [1 2 3 4 5 6]
   [1 4 9 16 25 36]))
2024-07-28T23:22:53.494908 image/svg+xml Matplotlib v3.7.1, https://matplotlib.org/

The pyplot function takes a Clojure function that creates a plot. It calls the function and returns an SVG plot. For example:

(pyplot/pyplot
 #(matplotlib.pyplot/plot
   [1 2 3 4 5 6]
   [1 4 9 16 25 36]))
2024-07-28T23:22:53.618517 image/svg+xml Matplotlib v3.7.1, https://matplotlib.org/

More examples

From the Parens for Pyplot tutorial

(require '[libpython-clj2.require :refer [require-python]]
         '[clojure.math :as math])
(require-python '[numpy :as np])
:ok
(def sine-data
  (let [x (range 0 (* 3 np/pi) 0.1)]
    (-> {:x (vec x)
         :y (mapv math/sin x)})))
(pyplot/with-pyplot
  (matplotlib.pyplot/plot
   (:x sine-data)
   (:y sine-data)))
2024-07-28T23:22:53.739354 image/svg+xml Matplotlib v3.7.1, https://matplotlib.org/
(pyplot/pyplot
 #(matplotlib.pyplot/plot
   (:x sine-data)
   (:y sine-data)))
2024-07-28T23:22:53.853042 image/svg+xml Matplotlib v3.7.1, https://matplotlib.org/

From the Seaborn intro:

(require-python '[seaborn :as sns])
:ok
(let [tips (sns/load_dataset "tips")]
  (sns/set_theme)
  (pyplot/pyplot
   #(sns/relplot :data tips
                 :x "total_bill"
                 :y "tip"
                 :col "time"
                 :hue "smoker"
                 :style "smoker"
                 :size "size")))
2024-07-28T23:22:54.362023 image/svg+xml Matplotlib v3.7.1, https://matplotlib.org/
(let [penguins (sns/load_dataset "penguins")]
  (sns/set_theme)
  (pyplot/pyplot
   #(sns/jointplot :data penguins
                   :x "flipper_length_mm"
                   :y "bill_length_mm"
                   :hue "species")))
2024-07-28T23:22:54.734626 image/svg+xml Matplotlib v3.7.1, https://matplotlib.org/
source: notebooks/index.clj