|
| 1 | +^{:kindly/hide-code true |
| 2 | + :clay |
| 3 | + {:title "Introduction to Violin Plots with Vega" |
| 4 | + :quarto {:author :mt |
| 5 | + :description "..." |
| 6 | + :image "overlayplot.png" |
| 7 | + :type :post |
| 8 | + :date "2025-11-24" |
| 9 | + :category :clojure |
| 10 | + :tags [:dataviz :vega-lite]}}} |
| 11 | + |
| 12 | +(ns scicloj.data-visualization.violin |
| 13 | + (:require |
| 14 | + [clojure.data.json :as json] |
| 15 | + [scicloj.kindly.v4.api :as kindly] |
| 16 | + [scicloj.kindly.v4.kind :as kind] |
| 17 | + )) |
| 18 | + |
| 19 | + |
| 20 | +;;; Get the movie dataset |
| 21 | +(def movie-data |
| 22 | + (json/read-str (slurp "https://vega.github.io/editor/data/movies.json") )) |
| 23 | + |
| 24 | + |
| 25 | +;;; Make a simple boxplot showing US Gross by Genre |
| 26 | +(kind/vega-lite |
| 27 | + {:mark {:type "boxplot" :tooltip {:content "data"}}, |
| 28 | + :data {:values movie-data} |
| 29 | + :encoding |
| 30 | + {"color" {:field "Major Genre", :type "nominal" :legend false}, |
| 31 | + "y" {:field "Major Genre", |
| 32 | + :type "nominal"}, |
| 33 | + "x" {:field "US Gross", |
| 34 | + :type "quantitative"} |
| 35 | + :tooltip {:field "Title" |
| 36 | + ;; :type "quantitative" |
| 37 | + }}, |
| 38 | + :width 800 |
| 39 | + }) |
| 40 | + |
| 41 | + |
| 42 | +;; That's nice, but how can we add violins to this? |
| 43 | +(kind/vega-lite |
| 44 | + {:mark {:type "area"}, |
| 45 | + :data {:values movie-data} |
| 46 | + :transform [{:density "US Gross" |
| 47 | + :groupby ["Major Genre"] |
| 48 | + :extent [0, 200000000]}] |
| 49 | + :encoding |
| 50 | + {"color" {:field "Major Genre", :type "nominal" :legend false}, |
| 51 | + "y" {:field "density", |
| 52 | + :type "quantitative" |
| 53 | + :stack "center" |
| 54 | + :axis false |
| 55 | + }, ;this reflect-doubles the area plot to produce the violin shape |
| 56 | + "x" {:field "value", |
| 57 | + :type "quantitative"} |
| 58 | + "facet" {:field "Major Genre" |
| 59 | + :type "nominal" |
| 60 | + :columns 1 |
| 61 | + :spacing 0 |
| 62 | + :legend :left |
| 63 | + } |
| 64 | + }, |
| 65 | + :width 800 |
| 66 | + }) |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + |
0 commit comments