"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...
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?
7 Answers
I had the same error, even if I was using aes(). So I used mapping argument before aes().
ggplot() +
geom_boxplot(df, mapping = aes(x = sp, y = cov))
Two mistakes:
- Brackets have to be closed after ggplot and calling histogram comes after
- you specify your data set when you call ggplot on
df. Therefore there is no need to adddf$sp.spis 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.
try
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)"
The main error is that you closed the bracket at the wrong place this is because we added geom.histogram as new function not an argument of ggplot. Instead, try below code
ggplot(df, aes(df$sp, df$cov)) + geom_histogram()