deepsense.aideepsense.ai logo
  • Careers
    • Job offers
    • Summer internship
  • Clients’ stories
  • Services
    • AI software
    • Team augmentation
    • AI advisory
    • Train your team
  • Industries
    • Retail
    • Manufacturing
    • Financial & Insurance
    • IT operations
    • TMT & Other
    • Medical & Beauty
  • Knowledge base
    • Blog
    • R&D hub
  • About us
    • Our story
    • Management
    • Advisory board
    • Press center
  • Contact
  • Menu Menu
How to create a new geom for ggplot2

How to create a new geom for ggplot2

December 17, 2015/in Data science /by Przemyslaw Biecek

The new version of the ggplot2 package (v 2.0.0) will be available on CRAN in a few days. It has a very nice mechanism for adding new geoms and stats (more about it here).

Let’s create a new geom geom_christmas_tree() that will plot data with the use of christmas trees instead of points. The geom will support following aesthetics: size, fill, color, x and y.
The size will be translated into the number of segments of each single tree. Width of a tree is fixed and height is proportional to the size.
Let’s start with an example.

# generate random positions, colors and sizes
mm = data.frame(matrix(runif(1200),300,4))
# plot
ggplot(mm, aes(X1, X2, size=X3, fill=X4)) +
geom_christmas_tree() +
theme_void() + scale_fill_gradient(low='green1', high='green4')

unif
One can combine this geom with other geoms (like contours).

ggplot(iris, aes(x=Sepal.Length, y=Petal.Length, size=Petal.Length, fill=Species)) +
stat_density_2d(aes(color=Species)) +
geom_christmas_tree() +
theme_void() + theme(legend.position="none")

iris2
And here we have the definition of the geom.

GeomChristmasTree = ggproto('GeomChristmasTree', Geom,
required_aes = c('x', 'y'),
default_aes = aes(shape = 19, colour = 'black',
fill = 'green4', size = 3,
linetype = 1, alpha = 1,
fontsize = 1),
draw_key = draw_key_polygon,
draw_panel = function(data, panel_scales, coord) {
coords = coord$transform(data, panel_scales)
# each tree is 4*branch + 4
if (length(coords$size) == 1) {
tsize = rep(pmax(1, round(coords$size)), length(coords$x))
theight = rep(pmax(0, round(coords$size)), length(coords$x))
} else {
tsize = pmax(1, round(coords$size))
theight = pmax(0, coords$size)
}
# the scale factor
r01x = diff(range(coords$x))/100
r01y = diff(range(coords$y))/100
# coords
longx = unlist(lapply(seq_along(coords$x), function(i) {
if (tsize[i] == 1) {
dx = -c(0.3, 0.3, 1.2, 0, -1.2, -0.3, -0.3)
} else {
dx = -c(0.3, 0.3, rep(c(1.2,0.3), tsize[i]-1), 1.2, 0, -1.2, rep(c(-0.3,-1.2), tsize[i]-1), -0.3, -0.3)
}
r01x*dx + coords$x[i]
}))
longy = unlist(lapply(seq_along(coords$y), function(i) {
if (tsize[i] == 1) {
dy = c(-0.5, 0, 0, theight[i], 0, 0, -0.5)
} else {
dy = c(-0.5, 0, 0, rep(1:(tsize[i]-1), each=2), theight[i], rep((tsize[i]-1):1, each=2), 0, 0, -0.5)
}
r01y*dy + coords$y[i]
}))
longid = unlist(sapply(seq_along(coords$y), function(i) {
rep(i, each=4*tsize[i]+3)
}))
grid::polygonGrob(
longx,
longy,
id = longid,
gp = grid::gpar(col = coords[,'colour'],
fill = coords[,'fill'],
fontsize = 10)
)
}
)
geom_christmas_tree = function(mapping = NULL, data = NULL, stat = 'identity',
position = 'identity', na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
geom = GeomChristmasTree, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
Share this entry
  • Share on Facebook
  • Share on Twitter
  • Share on WhatsApp
  • Share on LinkedIn
  • Share on Reddit
  • Share by Mail
https://deepsense.ai/wp-content/uploads/2019/02/How-to-create-a-new-geom-for-ggplot2.jpg 337 1140 Przemyslaw Biecek https://deepsense.ai/wp-content/uploads/2019/04/DS_logo_color.svg Przemyslaw Biecek2015-12-17 13:08:322021-01-05 16:52:02How to create a new geom for ggplot2

Start your search here

NEWSLETTER SUBSCRIPTION

    You can modify your privacy settings and unsubscribe from our lists at any time (see our privacy policy).

    This site is protected by reCAPTCHA and the Google privacy policy and terms of service apply.

    THE NEWEST AI MONTHLY DIGEST

    • AI Monthly Digest 20 - TL;DRAI Monthly Digest 20 – TL;DRMay 12, 2020

    CATEGORIES

    • Elasticsearch
    • Computer vision
    • Artificial Intelligence
    • AIOps
    • Big data & Spark
    • Data science
    • Deep learning
    • Machine learning
    • Neptune
    • Reinforcement learning
    • Seahorse
    • Job offer
    • Popular posts
    • AI Monthly Digest
    • Press release

    POPULAR POSTS

    • AI trends for 2021AI trends for 2021January 7, 2021
    • A comprehensive guide to demand forecastingA comprehensive guide to demand forecastingMay 28, 2019
    • What is reinforcement learning? The complete guideWhat is reinforcement learning? deepsense.ai’s complete guideJuly 5, 2018

    Would you like
    to learn more?

    Contact us!
    • deepsense.ai logo white
    • Services
    • Customized AI software
    • Team augmentation
    • AI advisory
    • Knowledge base
    • Blog
    • R&D hub
    • deepsense.ai
    • Careers
    • Summer internship
    • Our story
    • Management
    • Advisory board
    • Press center
    • Support
    • Terms of service
    • Privacy policy
    • Code of ethics
    • Contact us
    • Join our community
    • facebook logo linkedin logo twitter logo
    • © deepsense.ai 2014-
    Scroll to top

    This site uses cookies. By continuing to browse the site, you are agreeing to our use of cookies.

    OKLearn more

    Cookie and Privacy Settings



    How we use cookies

    We may request cookies to be set on your device. We use cookies to let us know when you visit our websites, how you interact with us, to enrich your user experience, and to customize your relationship with our website.

    Click on the different category headings to find out more. You can also change some of your preferences. Note that blocking some types of cookies may impact your experience on our websites and the services we are able to offer.

    Essential Website Cookies

    These cookies are strictly necessary to provide you with services available through our website and to use some of its features.

    Because these cookies are strictly necessary to deliver the website, refuseing them will have impact how our site functions. You always can block or delete cookies by changing your browser settings and force blocking all cookies on this website. But this will always prompt you to accept/refuse cookies when revisiting our site.

    We fully respect if you want to refuse cookies but to avoid asking you again and again kindly allow us to store a cookie for that. You are free to opt out any time or opt in for other cookies to get a better experience. If you refuse cookies we will remove all set cookies in our domain.

    We provide you with a list of stored cookies on your computer in our domain so you can check what we stored. Due to security reasons we are not able to show or modify cookies from other domains. You can check these in your browser security settings.

    Other external services

    We also use different external services like Google Webfonts, Google Maps, and external Video providers. Since these providers may collect personal data like your IP address we allow you to block them here. Please be aware that this might heavily reduce the functionality and appearance of our site. Changes will take effect once you reload the page.

    Google Webfont Settings:

    Google Map Settings:

    Google reCaptcha Settings:

    Vimeo and Youtube video embeds:

    Privacy Policy

    You can read about our cookies and privacy settings in detail on our Privacy Policy Page.

    Accept settingsHide notification only