Created
January 17, 2026 14:45
-
-
Save benkamphaus/42acc930af9197b6e68bd5fb7f357000 to your computer and use it in GitHub Desktop.
Basic java class lib only sin plot in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (ns biodecahedron.helpers.plots-from-scratch | |
| (:import [javax.swing JFrame JLabel ImageIcon] | |
| [java.awt.image BufferedImage] | |
| [java.awt RenderingHints] | |
| [java.awt Color] | |
| (java.io File) | |
| (javax.imageio ImageIO) | |
| (java.io File) | |
| (javax.imageio ImageIO))) | |
| (defn ->png | |
| [^BufferedImage img file-path] | |
| (let [output-file (File. ^String file-path)] | |
| (ImageIO/write img "png" output-file) | |
| (.getAbsolutePath output-file))) | |
| (defn display | |
| [^BufferedImage img ^String title] | |
| (let [frame (JFrame. title) | |
| icon (ImageIcon. img) | |
| label (JLabel. icon)] | |
| (.add (.getContentPane frame) label) | |
| (.pack frame) | |
| (.setVisible frame true) | |
| (.setDefaultCloseOperation frame JFrame/DISPOSE_ON_CLOSE))) | |
| (defn simple-unit-normal [vals] | |
| (let [max-v (apply max vals) | |
| min-v (apply min vals) | |
| v-bound (float (- max-v min-v))] | |
| (mapv | |
| (fn [v] | |
| (/ (- v min-v) v-bound)) | |
| vals))) | |
| (defn ->image-coords | |
| [{:keys [x y]} [w h] pad] | |
| (let [->nice-coord (fn [lim unit-v] | |
| (+ (* (- lim (* 2 pad)) unit-v) pad))] | |
| {:x (mapv (partial ->nice-coord w) (simple-unit-normal x)) | |
| :y (mapv (partial ->nice-coord h) (simple-unit-normal y))})) | |
| (defn data->plot-image | |
| [data opts] | |
| (let [width (get opts :width 1000) | |
| height (get opts :height 1000) | |
| {:keys [x y]} (->image-coords data [width height] 34) | |
| marker-size (get opts :marker-size 5) | |
| img (BufferedImage. width height BufferedImage/TYPE_INT_ARGB) | |
| g2d (.createGraphics img)] | |
| (.setRenderingHint g2d RenderingHints/KEY_ANTIALIASING RenderingHints/VALUE_ANTIALIAS_ON) | |
| (.setRenderingHint g2d RenderingHints/KEY_RENDERING RenderingHints/VALUE_RENDER_QUALITY) | |
| (.setRenderingHint g2d RenderingHints/KEY_STROKE_CONTROL RenderingHints/VALUE_STROKE_NORMALIZE) | |
| (.setColor g2d Color/BLUE) | |
| (doseq [[x0 y0] (map vector x y)] | |
| (.fillOval g2d x0 y0 marker-size marker-size)) | |
| (.dispose g2d) | |
| img)) | |
| (def plot-data | |
| (let [x-data (range 0 (* 2 Math/PI) 0.025) | |
| y-data (mapv (fn [x] | |
| (Math/sin x)) | |
| x-data)] | |
| {:x x-data | |
| :y y-data})) | |
| (comment | |
| (-> plot-data | |
| (data->plot-image {}) | |
| (display "Image Plot Example")) | |
| (-> plot-data | |
| (data->plot-image {:marker-size 10}) | |
| (->png "example.png"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment