Vindaar / ggplotnim

A port of ggplot2 for Nim
https://vindaar.github.io/ggplotnim
MIT License
177 stars 15 forks source link

multi subplots possible with vega? #155

Closed fbpyr closed 1 year ago

fbpyr commented 1 year ago

I saw rMultiSubplots.nim in the recipes, and would love to combine some plots to render them with vega. 🙂 Is this currently possible?

I tried:

...
let
  vegaHtmlPath = fmt"{node.lastPathPart}.html"
  firstPlot  = ggcreate(ggplot(df, aes(x="x_title",  y="y_title",  color="by_type")) + geom_bar())
  secondPlot = ggcreate(ggplot(df, aes(x="xx_title", y="yy_title", color="by_user")) + geom_bar())

var combinedPlots = initViewport(wImg=800, hImg=600, backend=bkVega)
combinedPlots.layout(1, rows = 2)
combinedPlots.embedAt(0, firstPlot .view)
combinedPlots.embedAt(0, secondPlot .view)
ggcreate(combinedPlots) + ggvega(vegaHtmlPath, show=false)

which fails, as combinedPlots is of type ViewType where ggcreate would need a GgPlot as input. 🤔 Would it be possible to create a GgPlot in a similar way and feed it to ggvega?

Vindaar commented 1 year ago

Nope, at the moment this is not supported yet using a nice interface.

You can do it by hand at the moment using the features I added in the last PR, but it requires a bit of manual work:

import ggplotnim
import ggplotnim/ggplot_vega
let mpg = readCsv("/home/basti/CastData/ExternCode/ggplotnim/data/mpg.csv")

let html1 = toVegaHtml(ggplot(mpg, aes(x = "displ", y = "cty", color = "class")) +
  geom_point() +
  ggtitle("plot 1"),
                       onlyBody = true,
                       divName = "vis1")
let html2 = toVegaHtml(ggplot(mpg, aes(x = "displ", y = "cty", color = "class")) +
  geom_point() +
  ggtitle("plot 2"),
                       onlyBody = true,
                       divName = "vis2")

let outfile = "/t/vega_multi_plot.html"
writeFile(outfile, embedVegaBody(html1 & html2))

import browsers
openDefaultBrowser(outfile)

which yields a page like:

image

Vindaar commented 1 year ago

If a different layout of the plots is desired, I suppose some CSS needs to be added. As I'm really not an expert on anything HTML & CSS related, I'm not keen on providing lots of functionality there. Happy to receive help and otherwise I'll probably add some basic interfacing to let users inject CSS of their own or something like that.

fbpyr commented 1 year ago

Thank you so much for the quick response and suggestion. This is a much nicer workaround than the one I had feared (merging the vega_json then building the html). 🙂 I will try it out.

fbpyr commented 1 year ago

Nice - Combining works well this way! 🙂 ( Only strange side effect are missing column colors in graphs 2 and 3, but that seems to be a separate topic, so I will open a different issue for that: #156 )