Fix in R: Cannot add ggproto objects together?

The ggproto objects cannot be combined together since they are not native R objects. Instead, ggplot2 provides several functions to manipulate ggproto objects, such as ggplot_add, ggplot_gtable, and ggplot_build, which can be used to combine them in a meaningful way. Additionally, it is recommended to use the ggplot() function to create ggproto objects in the first place.


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 package but forget to add a plus (+) sign somewhere in the syntax.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we have the following data frame in R that shows the number of total sales and customers that a store receives during 10 different days:

#create data frame
df <- data.frame(day = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                 sales = c(8, 8, 7, 6, 7, 8, 9, 12, 14, 18),
                 customers = c(4, 6, 6, 4, 6, 7, 8, 9, 12, 13))

#view data frame
df

   day sales customers
1    1     8         4
2    2     8         6
3    3     7         6
4    4     6         4
5    5     7         6
6    6     8         7
7    7     9         8
8    8    12         9
9    9    14        12
10  10    18        13

Now suppose we attempt to create a line chart to visualize the sales and customers during each of the 10 days:

library(ggplot2)

#attempt to create plot with two lines
ggplot(df, aes(x = day))
  geom_line(aes(y = sales, color = 'sales')) + 
  geom_line(aes(y = customers, color = 'customers'))

Error: Cannot add ggproto objects together.
       Did you forget to add this object to a ggplot object?

We receive an error that tell us we cannot add ggproto objects together.

How to Fix the Error

The way to fix this error is to simply add a plus sign (+) at the end of the first line, which we forgot to do the first time:

library(ggplot2)

#create plot with two lines
ggplot(df, aes(x = day)) +
  geom_line(aes(y = sales, color = 'sales')) + 
  geom_line(aes(y = customers, color = 'customers'))

The result is a plot with two lines that shows the total customers and sales during this 10-day period.

Notice that we don’t receive an error this time because we used a plus sign (+) at the end of the first line.

How to Fix in R: longer object length is not a multiple of shorter object length

x