“Error: Mapping should be created with `aes()` or `aes_()`.”

I’m trying to build a simple histogram with ggplot2 package in R. I’m loading my data from a csv file and putting 2 of the columns together in a data frame, like this:

df = data.frame(sp = data$species, cov = data$totalcover)

sp is recognised as a factor of 23 levels (my number of lines) and cov as 23 numbers. Then, to build the histogram, I’m executing this:

ggplot(df, aes(df$sp, df$cov) + geom_histogram())

However, R returns the error: “Error: Mapping should be created with aes() or aes_().”

How is this possible if I’m already using aes? Is it maybe related with the type of the values?

6 Answers

I had the same error, even if I was using aes(). So I used “mapping” before aes()

geom_boxplot (df, mapping = aes(x= sp, y= cov))

Two mistakes:

  1. Brackets have to be closed after ggplot and calling histogram comes after
  2. you specify your data set when you call ggplot on df. Therefore there is no need to add df$sp. sp is enough.

This code should work (if there is nothing wrong with your data):

    ggplot(df, aes(sp, cov)) + geom_histogram()

Do not use $ in aes. Only specify the dataset in ggplot. I used plot<-df %>% ggplot()

Yes, it works . You should not use the dollar sign $ if you have specified the data already. I had the same problem and when I removed the dollar sign, it worked.

ggplot(dat1, aes(Q84, REGION, fill = Q3)) +
  geom_bar(stat = "Identity") +
  facet_grid(REGION ~ Q84)

Avoid this:

ggplot(dat1, aes(dat1$Q84, dat1$REGION, fill = Q3)) +
  geom_bar(stat = "Identity") +
  facet_grid(dat1$REGION ~ Q84)

where dat1 is the name of my dataset.


ggplot(df, aes(df$sp, df$cov))+ geom_histogram()

instead of

ggplot(df, aes(df$sp, df$cov) + geom_histogram())

displacement of brackets

As another potential solution, I found that having library(cowplot) and library(ggplot2) loaded at the same time made “ggsave(“test.pdf”, p1)” not work.

Instead, use the cowplot syntax “save_plot(“test.pdf”, p1)”

Leave a Reply

Your email address will not be published. Required fields are marked *