maldini425
maldini425

Reputation: 317

Error with " Not an S3 object with class gg/ggplot"

I am getting the following error:

Error: data must be a data frame, or other object coercible by fortify(), not an S3 object with class gg/ggplot

And this is my code, which works perfectly with a different dataset:

household_income <- ggplot(household_income, aes(nationality, avg_income))
household_income + 
  geom_boxplot(aes(fill=factor(nationality))) + 
  geom_dotplot(binaxis='y', 
               stackdir='center',
               binwidth = 1,
               dotsize = .45, 
               fill="red") +
  theme(axis.text.x = element_text(angle=0, vjust=.9))

I am essentially trying to replicate the Box_Dot plot here

Upvotes: 1

Views: 968

Answers (1)

StupidWolf
StupidWolf

Reputation: 46948

You can also use the pipe (%>%) used often in dplyr to pass the data to ggplot

Making an example data.frame:

household_income = data.frame(
   nationality =sample(1:5,100,replace=TRUE),
   avg_income = rnbinom(100,mu=50,size=1)
)

Don't know your data.frame (so please provide it to make it a minimum reproducible example), for the geom_dotplot() and boxplot() to overlay, nationality has to be a factor. I used mutate() to factorize it on the fly below. And you set a lower alpha on the boxplot to see the dots:

library(ggplot2)
library(magrittr)

household_income %>% 
mutate(nationality=factor(nationality)) %>% 
ggplot(aes(nationality, avg_income))+ 
geom_boxplot(aes(fill=nationality),alpha=0.1) + 
geom_dotplot(binaxis='y',stackdir='center',dotsize=0.45,fill='red') + 
theme_bw()

enter image description here

Upvotes: 1

Related Questions