Fork me on GitHub
#nextjournal
<
2021-12-01
>
respatialized19:12:20

I'm trying to register a vega-lite viewer as a custom viewer for a fastmath distribution object so I can view it as a histogram instead of an object ref, but the result doesn't seem to show up:

(ns hist-demo
(:require [fastmath.random :as random]
          [nextjournal.clerk :as clerk]
          [nextjournal.clerk.viewer :as viewer]
)

(defn histogram [dist]
  {:data {:values (map (fn [v] {:value v}) (random/->seq dist 1250))}
   :width 125
   :height 125
   :mark {:type :bar}
   :encoding {:x {:field :value :bin true :axis {:title nil}}
              :y {:aggregate :count :axis {:title nil}}}})

(defn distribution? [v]
  (or (.isInstance org.apache.commons.math3.distribution.RealDistribution v)
      (.isInstance org.apache.commons.math3.distribution.IntegerDistribution v)
      (.isInstance org.apache.commons.math3.random.EmpiricalDistribution v)))

(distribution? (random/distribution :empirical {:data [0.3 0.4 0.5]}))
(clerk/with-viewers
  [{:pred distribution?
    :render-fn #(viewer/vl (histogram %))}]
  (random/distribution :empirical {:data [0.3 0.4 0.5]}))
(viewer/vl
 (histogram (random/distribution :empirical {:data [0.3 0.4 0.5]})))
The with-viewers form doesn't work, but the viewer/vl form does. It's not clear to me why.

mkvlr20:12:56

this is because the :render-fn be sent to the browser and evaluated there where it doesn’t have access to the histogram function. To make it work with with-viewers or clerk/set-viewers! you could use the :transform-fn histogram . :transform-fn is a function that will only run in Clojure and useful for situations like this. Both the docs & error messages still need a ton of work.

1
respatialized14:12:04

unfortunately, I am still having trouble even with :transform-fn :

mkvlr09:12:43

it should work if you do this with a transform-fn only, that is #(viewer/vl (histogram %)), this works here:

(ns viewers.vega
  (:require [nextjournal.clerk :as clerk]))

(clerk/set-viewers!
 [{:pred map?
   :transform-fn #(clerk/vl %)}])

{:width 650 :height 400 :data {:url ""
                               :format {:type "topojson" :feature "counties"}}
 :transform [{:lookup "id" :from {:data {:url ""}
                                  :key "id" :fields ["rate"]}}]
 :projection {:type "albersUsa"} :mark "geoshape" :encoding {:color {:field "rate" :type "quantitative"}}}

mkvlr09:12:39

or using with-viewers:

(clerk/with-viewers [{:pred map? :transform-fn #(clerk/vl %)}]
  {:width 650 :height 400 :data {:url ""
                                 :format {:type "topojson" :feature "counties"}}
   :transform [{:lookup "id" :from {:data {:url ""}
                                    :key "id" :fields ["rate"]}}]
   :projection {:type "albersUsa"} :mark "geoshape" :encoding {:color {:field "rate" :type "quantitative"}}})