rockdoctor
rockdoctor

Reputation: 545

ggplot - Bar Plot Aesthetics Error

I am just getting started with R and I am trying to plot some dummy data that I made which I have loaded as a dataframe, however, after a lot of trial and error and searching I tried to make a barplot of some of the columns and the following code did not work:

Termcount <- count(dummydata$Term)
ggplot(data=dummydata, aes(x=Term, y=Termcount, fill=Term)) + geom_bar(stat = "identity")

However, the following code did and generated the plot I was after but I can't understand why.

ggplot() + aes(dummydata$Term, fill=dummydata$Term) + geom_bar()

This generates the following plot:

enter image description here

When the first code is run I am presented with the following error:

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous. Error: Aesthetics must be either length 1 or the same as the data (17): x, y, fill

If required I can upload the data if that will help.

Upvotes: 0

Views: 9480

Answers (1)

Nate
Nate

Reputation: 10671

Like the comments above have said, ggplot() wants all of the aes() arguments to be column names in you data, dummydata, and that is why it's giving you the error. If you added your "count" variable as a new column it would work, something like this:

library(tidyverse)

data(iris)

dummy <- iris %>% count(Species)

ggplot(data = dummy, aes(Species, y = n, fill = Species)) +
    geom_bar(stat = "identity")

The above code is essentially what geom_bar() is doing "under the hood" in your second example because it defaults to using using stat = "count". FYI geom_col() is the stat = "identity" versions of geom_bar().

BTW welcome to SO, it always a good idea to include a tiny data example ( either via table format or dput() ) or use one of the built in data sets like data(iris). Example data plus example code and your expected output will allow people to help better and ensure that you are getting your specific problem solved.

Upvotes: 1

Related Questions