Vindaar / ggplotnim

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

simple pie chart possible? #162

Closed fbpyr closed 1 year ago

fbpyr commented 1 year ago

I read it is not in the list of supported geometries, but was wondering, if it might be still somehow possible to draw a simple pie chart with ggplotnim?

(ideally with vega backend, as it would be the last puzzle piece to completely port an existing python dataviz workflow from python 🐍 to nim 👑 )

Vindaar commented 1 year ago

Currently that's not really supported. In ggplot2 it would also normally be done by simply plotting a geom_bar using polar coordinates. However, I haven't implemented polar coordinates yet, so the equivalent is not an option. In vega it should apparently be done by using the arc encoding. The fact that it uses a field called theta makes me think the idea of polar coordinates is at least partially also how it's done in vega.

Purely supporting it in the vega backend would be pretty trivial (but would require adding a new GeomKind that has no equivalent on the normal backend, which makes me less of a fan).

Implementing polar coordinates in principle is straight forward, but there is complexity in the following points:

If you feel like it, try to hack around yourself in the Vega-Lite backend by replacing one of these mark kinds: https://github.com/Vindaar/ggplotnim/blob/master/src/ggplotnim/ggplot_vega.nim#L14-L23 by arc and one of these https://github.com/Vindaar/ggplotnim/blob/master/src/ggplotnim/ggplot_vega.nim#L85-L86 by theta and see what happens. Might produce the right plot.

I will think about if I can provide a semi decent way to support this / implement polar coordinates alternatively. Might take a bit though.

ggplot2: https://r-graph-gallery.com/piechart-ggplot2.html vega: https://vega.github.io/vega-lite/examples/arc_pie.html

fbpyr commented 1 year ago

@Vindaar thank you so much for elaborating! 🙂

right, for myself I would just use a simple bar chart add % text on it and be done. but since it is a port of an existing graph, I will try to replicate the pie chart as given. ( as worst case: writing the json for altair )

exactly mark_arc and theta are used over there - quite convenient api, I found:

pie_chart_on_topic = alt.Chart(all_hours_df).mark_arc(radius=150, innerRadius=50).encode(
    theta=alt.Theta("sum(total):Q", stack=True),
    color=alt.Color("topic:N", legend=alt.Legend(columns=1, symbolLimit=0,)),
    tooltip=["topic:N", "sum(total):Q"],
).properties(
    width=400,
    height=800,
    title=f"Overview: {topic}",
)

agreed, having a geom type that only exists for a bonus backend does seem strange. 🤔

thank you for the pointers - I will give it a shot. 😀