19
votes

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
You shouldn't use $ inside of aes(). Also histograms are univariate plots so you don't specify a y variable for those. Is your data already summarized? Maybe you want a bar chart? Try ggplot(df, aes(sp, cov) + geom_col(). If you the same message then it's possible you've overwritten the default aes() function. Take a look at conflicts() to see if you are shadowing the ggplot2::aes function. - MrFlick
Thank you very much! geom_col() does actually what I want and it doesn't return any error, so I think I haven't overwritten anything XD - Sonia Olaechea Lázaro

6 Answers

41
votes

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

ggplot()+
geom_boxplot (df, mapping = aes(x= sp, y= cov))
11
votes

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()
2
votes

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

0
votes

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.

0
votes

try

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

instead of

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

displacement of brackets

0
votes

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)"