Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add ggproto objects together and save for later without call to ggplot()?

Tags:

I would like to save some specifications of a ggplot command for later, given that I need to run several different graphs that all share some scale aesthetics.

Let's say I would like save this for later:

my.scale_aes <- scale_x_continuous(...) + scale_color_manual(...) 

This would of course prompt an error message, indicating that you cannot add ggproto objects together without a direct ggplot() call. But is that really the case? And is there another way by which I could still add these components together?

I read somewhere else that it has to do with the different methods of adding elements together: methods("+") and that what I need has something to do with +.gg* but I have no idea how to implement this and how to make it work.

like image 786
Fabian Habersack Avatar asked Jun 01 '19 10:06

Fabian Habersack


People also ask

Which operator allows you to add objects to a Ggplot?

Elements that are normally added to a ggplot with operator + , such as scales, themes, aesthetics can be replaced with the %+% operator.

What does cannot add ggproto objects together mean?

One error you may encounter in R is: Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object? This error typically occurs when you attempt to create a visualization using the ggplot2 package but forget to add a plus (+) sign somewhere in the syntax.

What is a Ggproto object?

ggproto implements a protype based OO system which blurs the lines between classes and instances. It is inspired by the proto package, but it has some important differences. Notably, it cleanly supports cross-package inheritance, and has faster performance.

What is geom in ggplot2?

Geoms. A layer combines data, aesthetic mapping, a geom (geometric object), a stat (statistical transformation), and a position adjustment. Typically, you will create layers using a geom_ function, overriding the default position and stat if needed.


1 Answers

You can do this by defining a list of the ggplot terms you want and adding them in.

library(ggplot2)  my.scale_aes <- list(   scale_x_continuous(breaks = c(56, 60, 61)),   scale_color_manual(values = c("black", "red")) )  ggplot(data = diamonds[1:100,],        aes(depth, price, color = cut == "Ideal")) +   geom_point() +   my.scale_aes  

enter image description here

like image 109
Jon Spring Avatar answered Sep 26 '22 03:09

Jon Spring